Question

I'm trying to use Capybara to select a drop down option, but it won't let me. The form is as follows:

  <%= simple_form_for @building do |f| %>
    <%= f.input :address  %>
    <%= f.input :city  %>
    <%= f.input :state, collection: ['AL', 'AK', 'AR', 'CA', 'CO', 'CT', 'DE', 'FL',
      'GA', 'HI', 'ID', 'IL', 'IN', 'IA', 'KS', 'KY', 'LA', 'ME', 'MD', 'MA', 'MI', 'MN', 'MS',
      'MO', 'MT', 'NE', 'NV', 'NH', 'NJ', 'NM', 'NY', 'NC', 'ND', 'OH', 'OK', 'OR', 'PA', 'RI', 'SC', 'SD', 'TN', 'TX', 'UT', 'VT', 'VA', 'WA', 'WV', 'WI', 'WY'] %>
    <%= f.input :zip  %>
    <%= f.input :description  %>
    <%= f.button :submit, "Add Building"  %>
  <% end %>

allowing you to select a from a dropdown of all the states in the USA. The code I am using in Capybara is as follows:

    fill_in 'Address', with: valid_attrs.address
    fill_in 'City', with: valid_attrs.city
    click_on 'building_state'
    click_on 'CT'
    fill_in 'Zip', with: valid_attrs.zip

but the "click on 'building_state' through to click_on 'CT' doesn't work.

Was it helpful?

Solution

To select an option from dropdown, you need to use select method and not click_on:

For example:

select 'CT', from: "building_state"

OTHER TIPS

Regarding the documentation:

The select box can be found via its name, id, test_id attribute, or label text. The option can be found by its text.

page.select 'March', from: 'Month'

When you have

<%= form.label :user_id %>
<%= form.collection_select :user_id, movie.assignable_users, :id, :full_name %>

this will result in the DOM element

<label for="movie_user_id">User</label>
<select name="movie[user_id]" id="movie_user_id" data-dashlane-rid="0d250b2b30fe033f" data-form-type="other">
  <option selected="selected" value="19">Kro Bo</option>
  <option value="18">Kas Brea</option>
</select>

Now you can read out any of html attributes named in the documentation and use them.

So

select 'Kro Bo', from: "movie_user_id"
select 'Kro Bo', from: "movie[user_id]"
select 'Kro Bo', from: "User"

will work.

When you use the label, make sure that the the for attribute of the label matches the id attribute of the html select element.

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