2012-03-22 71 views
6

我有一个方法,其中有一个开始/救援块。如何使用RSpec2测试救援块?使用RSpec我如何测试救援异常块的结果

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 
+1

仅供参考[为什么在Ruby中拯救Exception => e'不好的样式](https://stackoverflow.com/q/10048173/211563)。 – 2014-04-03 00:04:50

回答

8

使用should_receiveshould 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救出,这是默认设置。

+0

是的,但这不会引发异常。 – Nick 2012-03-22 22:47:09

+0

你的问题并没有真正要求那个部分,但我已经用它更新了我的问题,还有一个附加说明。 – 2012-03-22 23:03:02

+0

它具体询问**如何使用RSpec2测试救援块?** – Nick 2012-03-22 23:18:00