Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check select box has certain options with Capybara

People also ask

How do you select options in capybara?

Method: Capybara::Node::Actions#select If the select box is a multiple select, #select can be called multiple times to select more than one option. The select box can be found via its name, id, test_id attribute, or label text. The option can be found by its text.


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

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.


Well, since i was around and saw the question (and been testing today) decided to post my way:

within("select#cars") do
  %w(volvo saab mercedes audi).each do |option|
    expect(find("option[value=#{option}]").text).to eq(option.capitalize)
  end
end

Then I should see "audi" within "#cars"

should do the trick