如何记下rspec来测试救援块? [英] How to write down the rspec to test rescue block.?
问题描述
我有这样的方法
def className
def method_name
some code
rescue
some code and error message
end
end
那么,如何记下rspec来测试救援块??
So, How to write down the rspec to test rescue block..?
推荐答案
如果您想营救,则意味着您希望some code
引发某种异常.
If you want to rescue, it means you expect some code
to raise some kind of exception.
您可以使用 RSpec存根伪造实现并强行执行错误.假设执行块包含一个可能引发的方法
You can use RSpec stubs to fake the implementation and force an error. Assuming the execution block contains a method that may raise
def method_name
other_method_that_may_raise
rescue => e
"ERROR: #{e.message}"
end
在您的规范中将存根链接到该方法
hook the stub to that method in your specs
it " ... " do
subject.stub(:other_method_that_may_raise) { raise "boom" }
expect { subject.method_name }.to_not raise_error
end
您还可以通过测试结果来检查救援人员
You can also check the rescue handler by testing the result
it " ... " do
subject.stub(:other_method_that_may_raise) { raise "boom" }
expect(subject.method_name).to eq("ERROR: boom")
end
不用说,您应该提出一个可能由实际实现引发的错误,而不是一般性错误
Needless to say, you should raise an error that it's likely to be raised by the real implementation instead of a generic error
{ raise FooError, "boom" }
,并假设与此相关,则仅营救该Error
.
and rescue only that Error
, assuming this is relevant.
作为旁注,在Ruby中,您定义了一个类:
As a side note, in Ruby you define a class with:
class ClassName
不是
def className
如您的示例.
这篇关于如何记下rspec来测试救援块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!