Check select box has certain options with Capybara

Tom Maeckelberghe picture Tom Maeckelberghe · Mar 22, 2011 · Viewed 28.7k times · Source

How do I use Capybara to check that a select box has certain values listed as options? It has to be compatible with Selenium...

This is the HTML that I have:

<select id="cars"> 
  <option></option>
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="mercedes">Mercedes</option>
  <option value="audi">Audi</option>
</select>

This is what I want to do:

Then the "cars" field should contain the option "audi"

Answer

Jeff Perrin picture Jeff Perrin · Nov 22, 2011

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 selected
Then /^"([^"]*)" 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 present
Then /^"([^"]*)" should contain "([^"]*)"$/ do |dropdown, text|
  expect(page).to have_select(dropdown, :options => [text])
end