Search code examples
rubyrspec2rspec-rails

Using RSpec how can I test the results of a rescue exception block


I have a method that has a begin / rescue block in it. How do I test the rescue block using 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

Solution

  • Use should_receive and 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
    

    Also note that you should not be rescuing from Exception, but something more specific. Exception covers everything, which is almost definitely not what you want. At the most you should be rescuing from StandardError, which is the default.