How to get assert_raise to handle exception subclasses

Viewed 588

Sometimes I would like a unit test to confirm that some code raises an exception, without knowing the exception class exactly. For example, to confirm that it raises an exception which is a kind_of?(StandardError), I'd like to write this:

assert_raise StandardError do
  my_method
end

This assertion passes if the exception is an instance of StandardError, but fails if the exception is an instance of a subclass of StandardError. My best solution is this:



begin
  my_method
rescue StandardError => error
  return
end
assert false, "no error from my_method"

rescue does handle exception subclasses the way I want, so this works. But it's a little awkward. Any better ideas?

This is the Test::Unit::Assertions module in Ruby 1.8.7.

3 Answers
Related