Rails 7.1 allows matching exception messages to assert_raises assertion

railsOctober 25, 2023Dotby Alkesh Ghorpade

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.

Closing Remark

Could your team use some help with topics like this and others covered by ShakaCode's blog and open source? We specialize in optimizing Rails applications, especially those with advanced JavaScript frontends, like React. We can also help you optimize your CI processes with lower costs and faster, more reliable tests. Scraping web data and lowering infrastructure costs are two other areas of specialization. Feel free to reach out to ShakaCode's CEO, Justin Gordon, at [email protected] or schedule an appointment to discuss how ShakaCode can help your project!
Are you looking for a software development partner who can
develop modern, high-performance web apps and sites?
See what we've doneArrow right