If you only need to claim that the field is selected with the given option, a direct answer
#Find a select box by (label) name or id and assert the given text is selected When /^select box "([^"]*)" is selected with "([^"]*)"$/ do |dropdown, selected_text| assert page.has_select?(dropdown, selected: selected_text) end
Source: http://rubydoc.info/github/jnicklas/capybara/master/Capybara/Node/Matchers#has_select%3F-instance_method
But the name of your question is "Get the selection value for the drop-down list . " And I had a similar problem when I would like not only to approve the selection, but also to extract the text and value of the selected field. I did not find a direct path to the API. The easiest way I've found is: #all("option").find &:selected?
When /^ select box "([^"]*)" is selected with "([^"]*)"$/ do |dropdown, selected_text| sb = find_field(dropdown) sb_selected = sb.all("option").find &:selected? msg = "Selected: #{sb_selected.text.inspect} - value:#{sb_selected.value.inspect}" assert page.has_select?(dropdown, selected: selected_text), msg end
This gives me a more complete error message when the statement fails.
If there are several options, you can use #select instead of #find, as in #all("option").select &:selected? . It will return an array.
This answer does not rely on the 'option [selected]' trick as the previous one, so it works even if the selection is done by Javascript (which was the reason that the previous answers did not work for me at all).
Tested:
capybara (2.2.1) capybara-webkit (1.1.0) cucumber (1.3.14) cucumber-rails (1.4.0)
Abinoam jr. Jun 28 '14 at 15:58 2014-06-28 15:58
source share