Question

The problem I'm having (and I've tried all the solutions on the interwebs) is how to select an element from a grouped select with capybara.

Here's the dropdown:

<%= f.grouped_collection_select(:subcategory_id, Category.order(:name), :subcategories, :name, :id, :name, {}, { :class=> "form-control" }) %>

Here's one of the ways I've tried to select it.

select("Ortodoncista", from: 'provider[subcategory_id]')

The error

Unable to find option "Ortodoncista" (Capybara::ElementNotFound)
Was it helpful?

Solution

This answer worked for me Capybara: Select an option by value not text by @d_rail

You create a helper first. I put this helper in spec/support/utilities.rb

def select_by_value(id, value)
  option_xpath = "//*[@id='#{id}']/option[@value='#{value}']"
  option = find(:xpath, option_xpath).text
  select(option, :from => id)
end

Then to use it:

select_by_value "select_id", "select_option"

In my case, the select tag has the id user_category and the option I wanted to select was Musician. So my example was

select_by_value "user_category", "Musician"

OTHER TIPS

As I am more familiar with CSS selection, I would use:

This to find option element by its value, that correspond to the result of the option_key_method (:id), on a child of your collection (Categories):

 page.find('select#your-selectbox-id option[value="your-value"]')

This will return the desired capybara element found by your-value instead of searching by the text of the option. Then you can do whatever you want. for example: .text, or .click.

Or (just to remember) like this, if you want to select a given option from your selecbox with capybara:

select 'Option Label', :from => 'Selectbox Label Text'

wich, in your case would be the result of the option_value_method (:name) on a child of your collection (Categories).

Obs: reference for grouped selection

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top