本文介绍了使用 RSpec 如何测试救援异常块的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个方法,里面有一个开始/救援块.如何使用 RSpec2 测试救援块?
I have a method that has a begin / rescue block in it. How do I test the rescue block using RSpec2?
class Capturer
def capture
begin
status = ExternalService.call
return true if status == "200"
return false
rescue Exception => e
Logger.log_exception(e)
return false
end
end
end
describe "#capture" do
context "an exception is thrown" do
it "should log the exception and return false" do
c = Capturer.new
success = c.capture
## Assert that Logger receives log_exception
## Assert that success == false
end
end
end
推荐答案
使用 should_receive
和 should be_false
:
context "an exception is thrown" do
before do
ExternalService.stub(:call) { raise Exception }
end
it "should log the exception and return false" do
c = Capturer.new
Logger.should_receive(:log_exception)
c.capture.should be_false
end
end
另请注意,您应该不从 Exception
中拯救,而是更具体的东西.Exception
涵盖了一切,这几乎绝对不是您想要的.最多你应该从 StandardError
中解救出来,这是默认的.
Also note that you should not be rescuing from Exception
, but something more specific. Exception
covers everything, which is almost definitely not what you want. At the most you should be rescuing from StandardError
, which is the default.
这篇关于使用 RSpec 如何测试救援异常块的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!