首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何强制RSpec测试失败?

如何强制RSpec测试失败?
EN

Stack Overflow用户
提问于 2012-03-08 04:33:49
回答 3查看 16.4K关注 0票数 46

强制RSpec测试失败的正确方法是什么?

我在考虑1.should == 2,不过可能还有更好的东西。

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2012-03-08 04:44:19

fail/raise可以做到这一点(它们是彼此的别名)。

示例

代码语言:javascript
复制
specify "this test fails" do
  raise "this is my failure message"
end

失败,出现以下错误:

代码语言:javascript
复制
1) failing this test fails
   Failure/Error: raise "this is my failure message"

   RuntimeError:
     this is my failure message

替代方案

如果您正在考虑在规范中使用raise/fail,您应该考虑可能有更明确的方式来编写您的期望。

此外,raise/fail不能很好地处理aggregate_failures,因为异常会使代码块短路,并且不会运行任何后续的匹配器。

将测试标记为挂起

如果需要将测试标记为挂起以确保返回测试,则可以使用fail/raise,但也可以使用pending

代码语言:javascript
复制
#  Instead of this:
it "should do something" do
   # ...
   raise "this needs to be implemented"
end

# ✅ Try this:
it "should do something" do
  pending "this needs to be implemented"
end

断言某个块未被调用

如果您需要确保某个块不会被执行,请考虑使用yield matchers。例如:

代码语言:javascript
复制
describe "Enumerable#any?" do
  #  Instead of this:
  it "doesn't yield to the block if the collection is empty" do
    [].any? { raise "it should not call this block" }
  end

  # ✅ Try this:
  it "doesn't yield to the block if the collection is empty" do
    expect { |b| [].any?(&b) }.not_to yield_control
  end
end
票数 61
EN

Stack Overflow用户

发布于 2020-09-24 01:37:57

我知道很多年前就有人问过并回答过这个问题,但是RSpec::ExampleGroups有一个flunk方法。与在测试上下文中使用fail相比,我更喜欢这种flunk方法。使用fail有一个隐含的代码错误(您可以在这里看到更多信息:https://stackoverflow.com/a/43424847/550454)。

因此,您可以使用:

代码语言:javascript
复制
it 'is expected to fail the test' do
  flunk 'explicitly flunking the test'
end
票数 2
EN

Stack Overflow用户

发布于 2020-11-04 09:06:43

如果您想模拟RSpec期望失败而不是异常,那么您要查找的方法是RSpec::Expectations.fail_with

代码语言:javascript
复制
describe 'something' do
  it "doesn't work" do
    RSpec::Expectations.fail_with('oops')
  end
end

# => oops
#
# 0) something doesn't work
#    Failure/Error: RSpec::Expectations.fail_with('oops')
#      oops

请注意,尽管有文档,fail_with实际上并不直接引发ExpectationNotMetError,而是将其传递给私有方法RSpec::Support.notify_failure。这在使用aggregate_failures时很方便,它(在幕后)通过custom failure notifier工作。

代码语言:javascript
复制
describe 'some things' do
  it "sometimes work" do
    aggregate_failures('things') do
      (0..3).each do |i|
        RSpec::Expectations.fail_with("#{i} is odd") if i.odd?
      end
    end
  end
end

# => some things
# 
# Got 2 failures from failure aggregation block "things":
# 
#   1) 1 is odd
# 
#   2) 3 is odd
# 
#   0) some things sometimes work
#      Got 2 failures from failure aggregation block "things".
# 
#      0.1) Failure/Error: RSpec::Expectations.fail_with("#{i} is odd") if i.odd?
#             1 is odd
# 
#      0.2) Failure/Error: RSpec::Expectations.fail_with("#{i} is odd") if i.odd?
#             3 is odd
#     sometimes work (FAILED - 1)
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/9608624

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档