Skip to content

Instantly share code, notes, and snippets.

@tundal45
Created June 6, 2012 21:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tundal45/2885070 to your computer and use it in GitHub Desktop.
Save tundal45/2885070 to your computer and use it in GitHub Desktop.
How do I test if something is called in a rescue block?
class FooClass
def bar
baz
rescue StandardError => e
qux
raise
end
def baz
end
def qux
end
end
require_relative 'foo'
describe '#foo' do
it 'calls qux during exception' do
foo = FooClass.new
foo.stub(:baz).and_raise(StandardError)
foo.should_not_receive(:qux)
lambda{foo.bar}.should raise_error
end
end
# The test passes irrespective of if I have foo.should_receive(:qux) or foo.should_not_receive(:qux)
➜ rspec foo_spec.rb --format=documentation
#foo
calls qux during exception
Finished in 0.00443 seconds
1 example, 0 failures
@alindeman
Copy link

This is pretty sneaky!

RSpec uses exceptions to immediately raise an error when you call a method that's not expected. So when you call foo.qux within the rescue block, you're raising yet another exception: MockExpectationError. This bubbles up and satisfies the should raise_error, so the test passes.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment