2012-03-22 63 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