【问题标题】:How to test for multiple possible outcomes with have_content?如何使用 have_content 测试多种可能的结果?
【发布时间】:2022-02-17 23:26:23
【问题描述】:

我是测试新手,请耐心等待 :)

我想测试页面上的随机内容。例如,让我们测试页面是否显示“foo”或“bar”的内容。

下面是我想要实现的目标

page.should (have_content('foo') || have_content('bar'))

有什么想法吗?

【问题讨论】:

  • 恕我直言,您的问题的标题有点误导。它与统计无关。正确的?称之为“测试复杂条件”或其他什么(我不擅长制作标题)。想想其他人正在寻找您问题的答案。
  • 同意。希望新标题就足够了。

标签: rspec capybara


【解决方案1】:

我不知道任何准备好为您使用Mather。但是你可以自己烤。

使用satisfy:

page.should satisfy {|page| page.has_content?('foo') or page.has_content?('bar')}

simple_matcher

def have_foo_or_bar
  simple_matcher("check content has foo or bar") { |page| page.has_content?('foo') or page.has_content?('bar') }
end

describe page
  it "should have foo or bar" do
    page.should have_foo_or_bar
  end
end

编辑: has_content 接受正则表达式,因此您可以检查 page.should have_content(/foo|bar/)

【讨论】:

  • 使用满足工作。无法让 simple_matcher 工作,因为它正在吐出 NoMethodErrors。据我了解,该方法已被弃用?本来希望使用 simple_matcher 作为自定义错误消息。无论如何,感谢您的帮助!
  • 对,我给你的链接已经过时了。抱歉 :( 不知道为什么 Google 将它显示在顶部,应该更新它。:) 当前版本是 2.8 RSpec Expectations 2.8。最接近 simple_matcher 的是define matcher
【解决方案2】:

我也有同样的问题,但意识到在规范中添加 if 语句可能更容易且更有弹性。

it 'can complete my incredible form' do
  visit '/testing_path'
  #...dostuff...

  if object_im_testing.contains_my_condition?
    current_path.should eq('/special_condition_url')
  else
    current_path.should eq('/normal_condition_url')
  end
end

希望这有助于从另一个角度。最简单的解决方案通常是最好的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-11-28
    • 2023-03-22
    • 2017-03-26
    • 2021-07-21
    • 2020-04-21
    • 2019-04-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多