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

Ruby 使用RSpec如何测试救援异常块的结果,ruby,rspec2,rspec-rails,Ruby,Rspec2,Rspec Rails,我有一个方法,其中有一个begin/rescue块。如何使用RSpec2测试rescue块 class Capturer def capture begin status = ExternalService.call return true if status == "200" return false rescue Exception => e Logger.log_exception(e) return

我有一个方法,其中有一个begin/rescue块。如何使用RSpec2测试rescue块

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
使用和:


还要注意的是,您不应该从
异常中营救,而应该从更具体的方面营救<代码>例外
涵盖一切,这几乎肯定不是您想要的。最多你应该从默认的
StandardError
中解救出来。

是的,但这不会引发异常。你的问题并没有真正要求这一部分,但我已经用它更新了我的问题,还有一个附加说明。它特别问我如何使用RSpec2测试rescue block?你的标题特别提到“rescue block的结果”。没关系,我的更新答案有用吗?它可以工作,但是c.capture调用需要包装在lambda块中。谢谢我知道了。
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