Farooq Farooq - 3 months ago 58
Ruby Question

How to select option in drop down using Capybara

I'm trying to select an item from a drop down menu using Capybara (2.1.0).

I want to select by number (meaning select the second, third, etc option).

I've Googled like crazy trying all sorts of things but no luck.

I was able to select it by using the value:

find("option[value='4c430d62-f1ba-474f-8e8a-4452c55ea0a8']").click


But I don't want to use that method b/c the value is something that will change and that will make my test brittle.

The HTML for the drop down is:

<td class="value">
<select name="organizationSelect" id="organizationSelect" class="required">
<option value="NULL">Choose...</option>
<option value="4c430d62-f1ba-474f-8e8a-4452c55ea0a8">&nbsp;Institution1</option>
<option value="e1a4efa7-352d-410a-957e-35c8a3b92944">&nbsp;Institution / test</option>
</select>
</td>


I also tried this:

option = find(:xpath, "//*[@id='organizationSelect']/option[2]").text
select(option, :from => organizationSelect)


But it results in this error:

Ambiguous match, found 2 elements matching option "Institution" (Capybara::Ambiguous)


So how can I select the first, second, third, etc option from the drop down (using Capybara) ?

Answer

If you take a look at the source of the select method, you can see that what it does when you pass a from key is essentially:

find(:select, from, options).find(:option, value, options).select_option

In other words, it finds the <select> you're interested in, then finds the <option> within that, then calls select_option on the <option> node.

You've already pretty much done the first two things, I'd just rearrange them. Then you can tack the select_option method on the end:

find('#organizationSelect').find(:xpath, 'option[2]').select_option