Using MiniTest spec, I can test that code raises a specific exception as follows:
proc { foo.do_bar }.must_raise SomeException
But, I don't care what the specific exception is, I just want to verify that some exception is thrown. If I, or another developer, decides to change what exception is thrown by Foo#do_bar, my test wouldn't have to change if the expected exception was specified generally enough.
That is, I would like to write the test this way (Exception is an ancestor of class SomeException):
proc { foo.do_bar }.must_raise Exception
By this results in a failure when I run the test:
[Exception] exception expected, not
Class: <SomeException>
Can I write my Minitest spec more generically with regards to exceptions?
(The actual reason I want to check for any exception, rather than a specific exception, is that I'm using a third party Gem, and it is that code that raises the exception. In fact, my method A gets called by third party method B. A raises MyException, however B catches that exception, and re-raises a different exception. This exception has the same message as my exception [and this message is something I ought to verify in the test], but a different class.)
This seems odd behaviour.
From: http://bfts.rubyforge.org/minitest/MiniTest/Assertions.html#method-i-assert_raises
This checks the exception passed is an instance of
Module
and if so usese.kind_of?(ex)
which would work fine as as instance ofSomeException
will be of kindException
BUT only ifex
is a Module, soException
won't work. It needs to be something common that you have mixed into your exceptions.(As shown here http://ruby-doc.org/core-2.0/Object.html#method-i-kind_of-3F)
This matches minitests own tests ...
(From: https://github.com/seattlerb/minitest/blob/master/test/minitest/test_minitest_unit.rb )
So.. if your Exception mixes in a module, you can assert on the module.. but other than that go with @vgoff's answer.. or extend minitest to do what you want.
Note: I love that ruby is all open source!
Regardless, this should do pretty close to what you are asking for.