Hew Wolff
Hew Wolff

Reputation: 1509

How to get assert_raise to handle exception subclasses

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.

Upvotes: 4

Views: 631

Answers (3)

Chris Bloom
Chris Bloom

Reputation: 3564

This is essentially the same as what you started with, but is a little more self explanatory IMO:

begin
  my_method
rescue => e
  # Could be any number of error classes: 
  # HTTPClient::ConnectTimeoutError, SocketError, etc.
  assert e.class.ancestors.include?(StandardError), "Expected my_method to raise a subclass of StandardError, but #{e.class} was raised"
  return
end

# Force the test to fail if no error was raised
assert false, "Expected my_method to raise a subclass of StandardError, but no error was raised"

Upvotes: 1

ali
ali

Reputation: 404

As you can see in the rubyforge bugtracker ticket [#8716] Add option to Test::Unit::Assertions#assert_raise to allow subclasses from 2007(!) this is a feature request that's still open.

You could monkeypatch the functionality if you need it realy badly.

Upvotes: 2

Simone Carletti
Simone Carletti

Reputation: 176552

As far as I can see, the exception is optional in assert_raise

Tests if the given block raises an exception. Acceptable exception types maye be given as optional arguments.

You should be able to write

assert_raise { my_method }

Upvotes: 0

Related Questions