Trying to fillin second text box in capybara

2019-07-05 20:30发布

问题:

I am trying to fill in both textboxes that are labeled id="admin_passsword". I can access the first on easy but since there are NO differences other than the placeholder and the label above it I do not know how to access the second textbox to fill in that field.

<div class="fields">
    <div class="field-row">
      <label for="admin_email">Email</label>
      <input autocapitalize="off" id="admin_email" name="admin[email]" placeholder="Email" size="30" type="text" value="">
    </div>
    <div class="field-row">
      <label for="admin_serial_number">Serial number</label>
      <input id="admin_serial_number" name="admin[serial_number]" placeholder="Serial Number" size="30" type="text">
    </div>
    <div class="field-row">
      <label for="admin_password">Password</label>
      <input id="admin_password" name="admin[password]" placeholder="Password" size="30" type="password">
    </div>
    <div class="field-row">
      <label for="admin_password_confirmation">Password confirmation</label>
      <input id="admin_password" name="admin[password]" placeholder="Confirm Password" size="30" type="password">
    </div>
  </div>

回答1:

With Capybara 2.1, this works:

  fill_in("Password", with: '123456', :match => :prefer_exact)
  fill_in("Password confirmation", with: '123456', :match => :prefer_exact)

Prefer exact from the above comment's link: :prefer_exact is the behaviour present in Capybara 1.x. If multiple matches are found, some of which are exact, and some of which are not, then the first eaxctly matching element is returned.



回答2:

There are multiple ways to do it. Here are some of them:

In Capybara 2.0 you can do e.g. this:

all('label[for=admin_password_confirmation]').each {|field| field.set('123456')}

Capybara 2.1 supports new :exact option:

fill_in('Password', with: '123456', exact: true)
fill_in('Password Confirmation', with: '123456', exact: true)

But I'd recommend you to set:

# e.g. in features/support/env.rb
Capybara.configure do |config|
  config.exact = true # exact will be true by default in option hashes. It's false by default
end

# in your tests
fill_in('Password', with: '123456')
fill_in('Password Confirmation', with: '123456')


回答3:

You could also do a within block...

within('.class div:nth-child(div you want) do 
  fill_in("css", :with => "text")
end


标签: capybara