Search code examples
rubyrspectry-catchexpectations

Ruby Rspec message expectations for a caught exception


Is there any way with Rspec to set an expectation for an exception that gets caught? I want to verify that MyException gets raised, but since I am catching the exception Rspec does not appear to know it ever happened.

begin
  if success
    do good stuff
  else
    raise MyException.new()
  end
rescue MyException => e
  clean up
end

I've tried a few things like the following without success. MyException.should_receive(:new) and Kernel.should_receive(:raise).with(MyException)


Solution

  • I figured out how to do what I needed.

    class MyClass
      def my_method
        begin
          if success
            do good stuff
          else
            raise MyException.new
          end
        rescue MyException => e
          # clean up
        end
      end
    end
    
    describe MyClass do
      it "Expects caught exception" do
        my_instance = MyClass.new()
        my_instance.should_receive(:raise).with(any_instance_of(MyException))
        my_instance.my_method()
      end
    end
    

    Thanks for your other suggestions.