Given the following dropdown:
<select id="my-dropdown" name="my-dropdown">
<option value="1">Peter</option>
<option value="2" selected>Pan</option>
</select>
I know I can get the value (2 here) of the current selection using this code:
find_field("#my-dropdown").value
But how can I get the name/ label (Pan here) of the current selection? The following code does not work:
find_field("#my-dropdown").label
Thanks :)
You can use css3 selectors to find the selected item,
http://net.tutsplus.com/tutorials/html-css-techniques/the-30-css-selectors-you-must-memorize/
and call the 'text' method on the element to get the text.
http://rubydoc.info/github/jnicklas/capybara/master/Capybara/Node/Element:text
Try:
find_field('#my-dropdown option[selected]').text
While other answers came close, they did not seem to work with Capybara 1.1.2 (the version that I'm using). With that version I found that the following approach worked, but only because I knew what the value "should" be.
#based on Capybara::Node::Actions#select
def find_select_option(select_finder, option_finder)
no_select_msg = "cannot select option, no select box with id, name, or label '#{select_finder}' found"
no_option_msg = "cannot select option, no option with text '#{option_finder}' in select box '#{select_finder}'"
select = find(:xpath, XPath::HTML.select(select_finder), :message => no_select_msg)
select.find(:xpath, XPath::HTML.option(option_finder), :message => no_option_msg)
end
find_select_option('Countries', 'United States').should be_selected
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With