ruby-on-rails - 使用 capybara 测试表单 text_field 的存在

标签 ruby-on-rails forms capybara

我有以下表单,我想检查文本字段是否存在。我怎样才能做到这一点 ?

<%= 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 %>

这是我的测试:

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

最佳答案

您会使用 has_css? 期望:

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

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

您也可以使用其他 jQuery 样式的选择器来过滤输入字段上的其他属性。例如,'input[type="text"][name*="confirm"]' 会选择出现在输入字段的 nameconfirm 属性。

要设置字段不存在的期望值,您可以在期望值上使用to_not:expect(page).to_not have_css('input [type="text"]')

好处:这是较旧的 should 风格的语法:

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

关于ruby-on-rails - 使用 capybara 测试表单 text_field 的存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17880491/

相关文章:

ruby-on-rails - undef - 为什么要在 ruby​​ 中取消定义方法?

ruby-on-rails - 用于 rails ERB 模板的空白去除器?

python - django 和 dropzone 如何发布表单

ruby-on-rails - capistrano 中的主服务器

ruby-on-rails - 销毁 acts_as_votable 上的 UpVotes

javascript - 如何使用带有 "this"的 javascript 提交表单

jquery - 联系表单 7 Ajax/jquery 触发器无效 - 未触发

javascript - 配置 Turnip 和 Database_cleaner

ruby-on-rails - 访问 root_path 时出现 RSpec InfiniteRedirectError

ruby-on-rails-3 - 使用 simple_form Rails 时测试 HTML 5 表单验证