Rails 7.1 allows matching exception messages to assert_raises assertion
Asserting exceptions, errors, and the error messages you get is necessary to check in your test files. The minitest framework used by Rails provides support to assert error messages and exceptions raised.
But sometimes asserting, a long error message is unnecessary. The long error message spills over multiple lines. If the Rails application has enabled Rubocop for test files, developers need to spend some time fixing the Rubocop related issues.
Before Rails 7.1
Before Rails 7.1,
to verify the error
or
exception message raised,
you need to use the assert_match
method.
class UsersControllerTest < ActionDispatch::IntegrationTest
def test_normal_user_accessing_admin_dashboard
error = assert_raises(CustomError) do
get :admin
end
assert_match(
/You are not authorized to access this page/i,
error.message
)
end
end
As seen in the above example,
you can use a regex to match the error message.
But the issue is you need to use assert_raises
and
assert_match
functions.
The extra lines of code can be removed,
or
the two functions can be clubbed into a single method.
In Rails 7.1
Rails 7.1 adds the ability to match exception messages
to assert_raises assertion.
With this change,
you can pass the match
option as an argument to the assert_raises
method,
as shown below:
class UsersControllerTest < ActionDispatch::IntegrationTest
def test_normal_user_accessing_admin_dashboard
error = assert_raises(CustomError, match: /You are not authorized to access this page/i) do
get :admin
end
end
end
You can also pass a regex to match the error message. To know more about this feature, please refer to this PR.