Search code examples
ruby-on-railsrspeccapybara

How does fill_in work in Rspec/Capybara?


I am following Michael Hartl's Ruby on Rails Tutorial. When I use rspec/capybara, the fill_in method makes me confused. I have the following view code:

 <%= f.label :name %>   
 <%= f.text_field :name %>

This is my testing code:

 fill_in "Name", with: "Example User"

It seems that label and text_field are both required for fill_in to locate the input field. If I either take off f.label or change <%= f.text_field :name %> to be <%= f.text_field :another_name %>, the test will give me ElementNotFound error. Can anyone explain how the fill_in works here? Are input field and label both required for fill_in method?


Solution

  • It is stated that fill_in looks for field name, id or label text. According to ActionView::Helpers::FormHelper section of rails guides, the view code which you ask about should be translated to the following html code:

    # I assume that you made a form for a @user object
    <label for="user_name">
      Name
    </label>
    <input id="user_name" name="user[name]" type="text" />
    

    As you see, label produced the "Name" text, which you ask for inside of your fill_in expression. But id and name properties of input field are slightly different, so you should have been using id based selector to achieve the same result:

    fill_in "user_name", with: 'Example User'

    So, to sum up, label field is not required, but you should watch for your html code carefully and select the appropriate parameters for fill_in expression.