Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dropdown with selected item, how to get its name/ label using capybara

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 :)

like image 698
gucki Avatar asked Apr 19 '11 08:04

gucki


2 Answers

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
like image 73
noli Avatar answered Sep 27 '22 21:09

noli


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
like image 42
M. Scott Ford Avatar answered Sep 27 '22 21:09

M. Scott Ford