微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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中抢救,这是认值.

原文地址:https://www.jb51.cc/ruby/264706.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐