1

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)
brasofilo
  • 25,496
  • 15
  • 91
  • 179
freddyrangel
  • 1,353
  • 1
  • 11
  • 20
  • 2
    I recommend you use the `save_and_open_page` method and include the source code of the page to have a better understanding. – backpackerhh Mar 14 '14 at 16:21
  • That's a great idea. I'll do that next time :) – freddyrangel Mar 14 '14 at 16:43
  • 1
    @MauricioMoraes, I only marked your suggested edit as useful because of the nice improved title. You left lots of noise behind, check my edit. – brasofilo Apr 03 '14 at 12:02
  • 1
    That's way better! Just for freddyrangel to know, your question is a good one, but it wasn't very direct and had repeated information. Thanks brasofilo. – Mauricio Moraes Apr 03 '14 at 12:16

2 Answers2

2

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"
Community
  • 1
  • 1
Justin
  • 4,922
  • 2
  • 27
  • 69
1

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

Mauricio Moraes
  • 7,255
  • 5
  • 39
  • 59