使用RSpec如何测试救援例外块的结果

时间:2012-03-22 20:28:06

标签: ruby rspec2 rspec-rails

我有一个方法,里面有一个开始/救援块。如何使用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

1 个答案:

答案 0 :(得分:8)

使用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中抢救,但更具体。 Exception涵盖所有内容,这几乎绝对不是您想要的。您最多应该从StandardError开始营救,这是默认设置。