Capybara: How do I fill in a input field by its ID

RspecCapybara

Rspec Problem Overview


I have this:

<input class="string optional" 
    id="course_group_courses_attributes_2_name" 
    name="course_group[courses_attributes][2][name]" 
    placeholder="Lengua" 
    size="15" 
    type="text" />
</div> 

How do I fill in a that field by its ID?

Rspec Solutions


Solution 1 - Rspec

fill_in accepts the id as first parameter:

fill_in 'course_group_courses_attributes_2_name', :with => 'some text'

Solution 2 - Rspec

You can also do it with:

find('Id or class here').set('some text')

Solution 3 - Rspec

fill_in accepts id without the # symbol which I found confusing at first. Also note that if your input field is in a modal, you may need to wait for the transition or fade in before the field can be filled in.

Solution 4 - Rspec

If you're using simple_form gem then you must note that it does automatically id your form elements, hence manually id-ing elements yourself is futile!

There is; however, a naming convention that simple_form follows to id form elements.

object_attribute

So if you're filling-in information for let's say a contact object as follows:

= simple_form_for @contact do |f|
  = f.input :first_name
  = f.input :last_name

simple_form will then automatically generate ids to each form element respectively as so:

id="contact_first_name"
id="contact_last_name"

Now you can simply make use of this naming convention to fulfill all your fill_in needs. Hope this helps.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNerianView Question on Stackoverflow
Solution 1 - RspecraidfiveView Answer on Stackoverflow
Solution 2 - Rspecuser2322409View Answer on Stackoverflow
Solution 3 - RspecStrangegrooveView Answer on Stackoverflow
Solution 4 - RspecmoeabdolView Answer on Stackoverflow