Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Capybara/CSS: How to find an input field by label AND value?

Tags:

css

capybara

I need to fill in an input field in Capybara/RSpec.

<div class="form-group control_center_operators_name">    
  <label class="control-label"  
         for="control_center_operators_attributes_1477562669357_name">
    Name
  </label>       
  <input class="form-control"
       type="text" value=""          
       name="control_center[operators_attributes][1477562669357][name]" 
       id="control_center_operators_attributes_1477562669357_name" />
</div>

My problem is, that there are more fields like this, where the user can edit existing operators. e.g.

<div class="form-group control_center_operators_name">    
  <label class="control-label"  
         for="control_center_operators_attributes_0_name">
    Name
  </label>
  <input class="form-control" 
         type="text" value="ABC"          
         name="control_center[operators_attributes][0][name]" 
         id="control_center_operators_attributes_0_name" />
</div>

What I know about the field:

  • it is labeled "Name"
  • its value is "" (empty)

More restrictions:

  • there are a total of 4 fields in this set (name, phone, email, homepage), that means I can't just take the one with value='' as there are 4 input fields matching this query.
  • I can't use the id and name attributes, as you can see.

How can I fill the empty name, phone, email and homepage fields with Capybara/CSS?

like image 671
Flip Avatar asked Jan 17 '26 15:01

Flip


1 Answers

The Capybara method for finding a field is #find_field. You can filter by value too with the :with option

find_field('Name', with: '').set('new value to set')

Note that will match against the current value property of the element, which may not be the same as the value attribute if the value of the field has been changed since page load. Another option is to scope to a wrapper element that would make the field unique and then find within that element. For instance if each of these sets of fields was in a div with class of operator and you wanted to fill in the name in the the last operator set you could do

all('.operator', minimum: 1).last.fill_in('Name', with: 'new value to set')

Update: As of Capybara 3 all has waiting behavior by default so the minimum option would not be needed

all('.operator').last.fill_in('Name', with: 'new value to set')
like image 191
Thomas Walpole Avatar answered Jan 20 '26 19:01

Thomas Walpole



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!