簡體   English   中英

使用RSpec如何測試救援例外塊的結果

[英]Using RSpec how can I test the results of a rescue exception block

我有一個方法,其中包含一個開始/救援塊。 如何使用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搶救,這是默認值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM