Source: minitest/minitest#440 (comment)
kytrinyx commented on Jul 15, 2014 I would highly recommend separating out the two tests, and on the one hand asserting that your code handles the exception in the way you want it to, and on the other hand, that a collaborator calls the method that you expect it to call (without making assertions about what happens when it does).
Here's an example of the first type of test, using a stub:
class Cupcake
class SpectacularError < RuntimeError; end
def serve
# stuff and logic
with_sprinkles
rescue SpectacularError
"oops"
end
def with_sprinkles
# does sprinkly stuff
end
end
class TestStuff < Minitest::Test
def test_exception_handling
cupcake = Cupcake.new
error = ->{ raise Cupcake::SpectacularError.new("spectacular sprinkle fail") }
cupcake.stub(:with_sprinkles, error) do
assert_equal "oops", cupcake.serve
end
end
end
The second is a straight-forward mock, and it wouldn't contain an exception.
For a really good explanation of why you might want to do this, see this talk by Sandi Metz: https://www.youtube.com/watch?v=URSWYvyc42M