Capybara: Select an option by value not text

2019-01-31 10:21发布

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

标签: ruby capybara
8条回答
爷的心禁止访问
2楼-- · 2019-01-31 10:49

You can also achieve it by doing the following:

find_by_id('date').find("option[value='20120905']").click
查看更多
Emotional °昔
3楼-- · 2019-01-31 10:55

In my case I have a few options with same text, that's the reason why I need select by value. Combining a few answers together I've found the best solution for me:

def select_by_value(id, value)
  option_xpath = "//*[@id='#{id}']/option[@value='#{value}']"
  find(:xpath, option_xpath).select_option
end
查看更多
▲ chillily
4楼-- · 2019-01-31 11:00

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

查看更多
Lonely孤独者°
5楼-- · 2019-01-31 11:02

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
查看更多
6楼-- · 2019-01-31 11:06

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
查看更多
霸刀☆藐视天下
7楼-- · 2019-01-31 11:07

That helper method pretty clever. I would change it a little:

def select_by_value(id, value)

  option_xpath = "//*[@id='#{id}']/option[@value='#{value}']"

  find(:xpath, option_xpath).click

end

or just:

find(:xpath, "//select[@id='date']/option[@value='20120904']").click
查看更多
登录 后发表回答