Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Capybara: Select an option by value not text

Tags:

ruby

capybara

For the HTML

<select id="date">
  <option value="20120904">Tue 4 Sep 2012</option>
  <option value="20120905">Wed 5 Sep 2012</option>
  <option value="20120906">Thu 6 Sep 2012</option>
</select>

I have the following Capybara Ruby code:

select "20120905", :from => "date"

But this errors with:

cannot select option, no option with text '20120905' in select box 'date' (Capybara::ElementNotFound)

However, if I do

select "Wed 5 Sep 2012", :from => "date"

It's ok.

Is it possible to select an option in Capybara by Value not Text?

Thanks

like image 483
Paul Avatar asked Sep 04 '12 14:09

Paul


4 Answers

This will work to select an option by value:

find("option[value='20120905']").click

To maintain the scope of the selector you could wrap it in a within block as such:

within '#date' do
  find("option[value='20120905']").click
end
like image 184
robynhenderson Avatar answered Nov 05 '22 05:11

robynhenderson


With Poltergeist as driver I can't click on an option like suggested in some of the other options above, instead you can do the following:

page.find_by_id('date').find("option[value='20120905']").select_option

like image 24
Mark Avatar answered Nov 05 '22 05:11

Mark


I wrote a helper method:

def select_by_value(id, value)
  option_xpath = "//*[@id='#{id}']/option[@value='#{value}']"
  option = find(:xpath, option_xpath).text
  select(option, :from => id)
end

Save in a .rb file in spec/support/

Example use:

before do
  select_by_value 'some_field_id', 'value'
  click_button 'Submit'
end
like image 21
d_rail Avatar answered Nov 05 '22 04:11

d_rail


You can also achieve it by doing the following:

find_by_id('date').find("option[value='20120905']").click
like image 4
TrashyMcTrash Avatar answered Nov 05 '22 05:11

TrashyMcTrash