What is the expected syntax for checking exception messages in MiniTest's assert_raises
/must_raise
?
I'm trying to make an assertion something like the following, where "Foo"
is the expected error message:
proc { bar.do_it }.must_raise RuntimeError.new("Foo")
Minitest does not provide (yet) you a way to check the actual exception message. But you could add a helper method that does it and extend
ActiveSupport::TestCase
class to use everywhere in your rails test suite, e.g.: intest_helper.rb
and use it in your tests like:
To add some more recent developments, there have been some discussions on adding
assert_raises_with_message
to minitest in the past without much luck.Currently, there is a promising pull request waiting to be merged. If and when it gets merged, we will be able to use
assert_raises_with_message
without having to define it ourselves.In the meanwhile, there is this handy little gem named minitest-bonus-assertions which defines exactly that method, along with few others, so that you can use it out of the box. See the docs for more information.
You can use the
assert_raises
assertion, or themust_raise
expectation.If you need to test something on the error object, you can get it from the assertion or expectation like so:
To assert exception:
To assert exception message:
As per API doc,
assert_raises
returns the exception matched so you can check the message, attributes, etc.