What's the proper way to force an RSpec test to fail?
我在考虑1.should == 2
英镑,不过可能还有更好的.
What's the proper way to force an RSpec test to fail?
我在考虑1.should == 2
英镑,不过可能还有更好的.
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