Verifying errors are raised is handy, but are you sure you’re capturing the right one?

Check the message!

# assert_raise allows you to check for the type of an error but not to check the error messages contents
# This is a wrapper to assert_raise that adds this functionality.
#
# Use with the traditional assert_raise syntax
# http://www.ruby-doc.org/stdlib/libdoc/test/unit/rdoc/classes/Test/Unit/Assertions.html
#
# To specify the error message, provide a string or regular expression to the :error_message option
#
# Example
# assert_raise_with_error_message ArgumentError, :error_message => /is not refuelable$/ do
#   outfitter.refuel(Asteriod.new)
# end
#
class Test::Unit::TestCase
  def assert_raise_with_error_message *args, &block
    options = args.last.kind_of?(Hash) ? args.pop : {}
    exception = assert_raise *args, &block
    expected_message = options[:error_message]
    case expected_message
    when String
      assert_equal expected_message, exception.message
    when Regexp
      assert_match expected_message, exception.message
    end
  end
end

Leave a Comment

Enclose code in <code lang="ruby"></code> if you care.
Preview your comment using the button below.