Created
June 6, 2012 21:53
-
-
Save tundal45/2885070 to your computer and use it in GitHub Desktop.
How do I test if something is called in a rescue block?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class FooClass | |
def bar | |
baz | |
rescue StandardError => e | |
qux | |
raise | |
end | |
def baz | |
end | |
def qux | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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 theshould raise_error
, so the test passes.