繁体   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