简体   繁体   中英

Test a form text_field presence with capybara

I have the following form and I want to check if the text field is present or not. How can I do that ?

<%= form_for(ownership, remote: true) do |f| %>
  <div>
    <%= f.text_field :confirm, value: nil %>
    <%= f.hidden_field :start_date, value: Time.now %>
  </div>
  <%= f.submit t('button.ownership.take.confirmation'), class: "btn btn-small"%>
<% end %>

Here my test :

describe "for not confirmed ownership" do

  before do
    FactoryGirl.create(:agreed_ownership, user: current_user, product: product)
    be_signed_in_as(current_user)
    visit current_page
  end

  # it { should_not have_text_field(confirm) }
  it { should_not have_button(t('button.ownership.take.confirmation')) }
end

You'd use a has_css? expectation:

it "should have the confirm input field" do
  visit current_page

  expect(page).to have_css('input[type="text"]')
end

You can use additional jQuery-style selectors to filter for other attributes on the input field, too. For example, 'input[type="text"][name*="confirm"]' would select for confirm appearing in the input field's name attribute.

To set an expectation the field isn't present, you'd use to_not on your expectation: expect(page).to_not have_css('input[type="text"]')

Bonus : Here's the older, should -style syntax:

it "should have the confirm input field" do
  visit current_page

  page.should have_css('input[type="text"]')
end

it "shouldn't have the confirm input field" do
  visit current_page

  page.should_not have_css('input[type="text"]')
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM