强制RSpec测试失败的正确方法是什么?
我在考虑1.should == 2
,不过可能还有更好的东西。
发布于 2012-03-08 04:44:19
fail
/raise
可以做到这一点(它们是彼此的别名)。
示例
specify "this test fails" do
raise "this is my failure message"
end
失败,出现以下错误:
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
。
# 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。例如:
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
发布于 2020-09-24 01:37:57
我知道很多年前就有人问过并回答过这个问题,但是RSpec::ExampleGroups
有一个flunk
方法。与在测试上下文中使用fail
相比,我更喜欢这种flunk
方法。使用fail
有一个隐含的代码错误(您可以在这里看到更多信息:https://stackoverflow.com/a/43424847/550454)。
因此,您可以使用:
it 'is expected to fail the test' do
flunk 'explicitly flunking the test'
end
发布于 2020-11-04 09:06:43
如果您想模拟RSpec期望失败而不是异常,那么您要查找的方法是RSpec::Expectations.fail_with
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工作。
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)
https://stackoverflow.com/questions/9608624
复制相似问题