ruby – 使用RSpec如何测试救援异常块的结果

我有一个方法,其中包含一个开始/救援块.如何使用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_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中抢救,而是更具体.例外涵盖了一切,几乎绝对不是你想要的.您最多应该从StandardError中抢救,这是认值.

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...