Check select box has certain options with Capybara Check select box has certain options with Capybara ruby-on-rails ruby-on-rails

Check select box has certain options with Capybara


Try using the capybara rspec matcher have_select(locator, options = {}) instead:

#Find a select box by (label) name or id and assert the given text is selectedThen /^"([^"]*)" should be selected for "([^"]*)"$/ do |selected_text, dropdown|  expect(page).to have_select(dropdown, :selected => selected_text)end#Find a select box by (label) name or id and assert the expected option is presentThen /^"([^"]*)" should contain "([^"]*)"$/ do |dropdown, text|  expect(page).to have_select(dropdown, :options => [text])end


For what it's worth, I'd call it a drop-down menu, not a field, so I'd write:

Then the "cars" drop-down should contain the option "audi"

To answer your question, here's the RSpec code to implement this (untested):

Then /^the "([^"]*)" drop-down should contain the option "([^"]*)"$/ do |id, value|  page.should have_xpath "//select[@id = '#{id}']/option[@value = '#{value}']"end

If you want to test for the option text instead of the value attribute (which might make for more readable scenarios), you could write:

  page.should have_xpath "//select[@id = '#{id}']/option[text() = '#{value}']"


As an alternative solution, and as I'm not familiar with xpaths, I did this to solve a similar problem:

page.all('select#cars option').map(&:value).should == %w(volvo saab mercedes audi)

Its quite simple, but took me some time to figure out.