Skip to content

Instantly share code, notes, and snippets.

@hmistry
Created October 31, 2017 02:28
Show Gist options
  • Save hmistry/18264a7b0e9fd45cfc0e560bc8e82008 to your computer and use it in GitHub Desktop.
Save hmistry/18264a7b0e9fd45cfc0e560bc8e82008 to your computer and use it in GitHub Desktop.
Minitest stub to raise exception

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

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