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?
Best Answer
It is stated that
fill_in
looks for fieldname
,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:As you see,
label
produced the "Name" text, which you ask for inside of yourfill_in
expression. Butid
andname
properties ofinput
field are slightly different, so you should have been usingid
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 forfill_in
expression.