迫使RSpec测试失败的正确方法是什么?
我正在考虑1.should == 2
但是可能还有更好的东西。
答案 0 :(得分:55)
fail
/ raise
可以解决问题(它们是彼此的别名)。 pending
也很有用。
示例:
it "should do something" do
pending "this needs to be implemented"
end
答案 1 :(得分:2)
我知道这是很多年前提出并回答的,但是RSpec::ExampleGroups
有一种flunk
方法。在测试的上下文中,我更喜欢这种flunk
方法而不是使用fail
。使用fail
隐含代码失败(您可以在此处查看更多信息:https://stackoverflow.com/a/43424847/550454)。
因此,您可以使用:
it 'is expected to fail the test' do
flunk 'explicitly flunking the test'
end
答案 2 :(得分:1)
如果要模拟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)