【问题标题】:Cucumber/Capybara: check that a page does NOT have content?Cucumber/Capybara:检查页面是否没有内容?
【发布时间】:2012-08-16 02:54:56
【问题描述】:

使用 Cucumber 和 Capybara,有没有办法验证页面上不存在字符串?

比如这个步骤的反面怎么写:

Then /^I should see "(.*?)"$/ do |arg1|
  page.should have_content(arg1)
end

如果存在arg1,则通过。

如果找到arg1,我将如何编写失败的步骤?

【问题讨论】:

    标签: ruby-on-rails cucumber capybara


    【解决方案1】:

    http://rubydoc.info/github/jnicklas/capybara/master/Capybara/Node/Matchers#has_no_text%3F-instance_method

    Capybara 中有一个has_no_content 匹配器。所以你可以写

      Then /^I should not see "(.*?)"$/ do |arg1|
        page.should have_no_content(arg1)
      end
    

    【讨论】:

    【解决方案2】:

    在目前(2016 年)的 Rspec 3.4 中,这是测试没有内容的推荐方法:

    expect(page).not_to have_content(arg1)
    

    【讨论】:

    • 您在哪里看到比expect(page).to have_no_content(arg1) 更推荐?似乎 not_to 没有办法知道不等待内容出现在页面上,这就是 have_content 会做的事情,我想。
    • 使用“expect(page).to have_no_content(arg1)”时会显示弃用警告
    • @RobHughes,您所说的折旧警告必须已在 rspec 3.5.4/capybara 2.6.2 中删除。根据文档:github.com/teamcapybara/… - Capybara's RSpec matchers, however, are smart enough to handle either form. The two following statements are functionally equivalent: expect(page).not_to have_xpath('a'), expect(page).to have_no_xpath('a')
    【解决方案3】:

    如果你想让它读起来更好一点,你也可以使用 should_not

    Then /^I should not see "(.*?)"$/ do |arg1|
      page.should_not have_content(arg1)
    end
    

    更多信息:https://www.relishapp.com/rspec/rspec-expectations/docs

    【讨论】:

    • 请注意,如果您的规范中包含 Capybara::RSpecMatchers,这仅适用于 javascript 测试。我刚刚在这里遇到了这个问题:stackoverflow.com/a/15253235/125377
    • 请改用has_no_content?。这将触发水豚的内部等待。否则,如果您正在等待内容从页面中消失,它将提前失败。
    【解决方案4】:

    目前,您可以使用:

    Then /^I not see "(.*?)"$/ do |arg1|
      expect(page).to have_no_content(arg1)
    end
    

    如果在页面中找到内容,你的测试是红色的

    【讨论】:

    • 这是正确的语法。如果您使用的是 expect(),我会改写您的规范,从描述中删除“应该”。更有主见! :)
    • 谢谢@Rimian。我修好了!
    【解决方案5】:

    哦,等等,我想通了。这有效:

    Then /^I should see "(.*?)"$/ do |arg1|
      page.has_content?(arg1) == false
    end
    

    【讨论】:

    • 您的代码没有断言内容。我猜如果你把 false 改成 true,你的测试还是会通过的。
    • 这让我绊倒了好几次。要么你使用assert page.has_content... 要么page.should have_content... 不能将两种样式混合在一起。好电话,@PhilippeRathé。
    猜你喜欢
    • 1970-01-01
    • 2015-11-13
    • 2021-04-30
    • 1970-01-01
    • 2017-07-03
    • 2012-04-07
    • 1970-01-01
    • 2014-10-22
    • 1970-01-01
    相关资源
    最近更新 更多