13

I am having some very strange behaviour with Capybara. It stubbornly refuses to fill in the fields of my login form.

<fieldset>
  <div class="clearfix">
    <label for="user_email">E-Mail Adresse</label>
    <div class="input">
      <input id="user_email" name="user[email]" size="30" type="email" value="">
    </div>
  </div>

  <div class="clearfix">
    <label for="user_password">Passwort</label>
    <div class="input">
      <input id="user_password" name="user[password]" size="30" type="password" value="">
    </div>
  </div>

  <div class="clearfix">
    <div class="input">
      <input name="user[remember_me]" type="hidden" value="0">
      <input id="user_remember_me" name="user[remember_me]" type="checkbox" value="1">
      <label for="user_remember_me">angemeldet bleiben</label>
    </div>
  </div>
</fieldset>

And here is where the fun begins:

within("#login_form"){ find("#user_email")}                                              
=> #<Capybara::Element tag="input" path="/html/body/div[2]/div[@id='content']/div/div[1]/form[@id='login_form']/fieldset/div[1]/div/input[@id='user_email']">
within("#login_form"){ fill_in("#user_email", with: "foo@example.com")}                  
Capybara::ElementNotFound: Unable to find field "#user_email"

I don't quite understand how it is possible to be able to find, and yet not find, an element. Another pair of eyes on this would be appreciated.

Justin Ko
  • 46,526
  • 5
  • 91
  • 101
mikewilliamson
  • 24,303
  • 17
  • 59
  • 90

3 Answers3

26

The locator for find and fill_in are different:

  • find - When the first parameter is not a symbol, it is assumed to be the Capybara.default_selector - ie a css-selector or xpath.
  • fill_in - The first parameter is the field's name, id or label text.

The string "#user_email" represents a css-selector. This is why it works in find but not fill_in.

For fill_in to work, you need to just pass in the id value - ie just "user_email".

within("#login_form"){ fill_in("user_email", with: "foo@example.com")}  
Justin Ko
  • 46,526
  • 5
  • 91
  • 101
  • Hi @Justin Ko , I m working on a framework where in all locator values are stored in an excel and hence I'd be interested in using the element already found using 'find' to perform any action..as i'll have no freedom to again check on other attributes of that element just for 'fill_in' Is there any alternate? – Aks.. Aug 19 '14 at 09:05
  • Just wanted to know if I can fill in data to a form field found using `find`. I guess answer is using of `#set`. – Aks.. Aug 20 '14 at 02:50
10

you can do find("#user_email").set "foo@example.com". See answer https://stackoverflow.com/a/8544650/3163914

Community
  • 1
  • 1
Jeff
  • 1,214
  • 1
  • 12
  • 23
1

if it is an autocomplete field, you can use this:

  def fill_in_autocomplete(id, value)
    page.execute_script("document.getElementById('#{id}').setAttribute('value', '#{value}');")
  end

edymerchk
  • 1,203
  • 13
  • 19