In a Ruby on Rails project, I want to assert on the exception message in my code to make sure it fails for the right reason and mentions important details.
Here is a function that always raises:
class Quiz < ApplicationRecord
def self.oops
raise ArgumentError.new("go away")
end
end
The test:
require "test_helper"
class QuizTest < ActiveSupport::TestCase
test "error message" do
assert_raises(ArgumentError, match: /whatever/) do
Quiz.oops()
end
end
end
When I run bin/rake test
, this passes, but I expected it to fail cause the actual error message doesn't match the match
in assert_raises
.
How can I capture the error message and assert against it?
I think you can use a little different approach (capture the error message using a block and then assert on the message content):
test "error message" do
exception = assert_raises(ArgumentError) do
Quiz.oops()
end
assert_match(/whatever/, exception.message)
end