Rails 7.1 now allows matching exception messages to assert_raises assertion.

While writing minitests or rspec tests in Rails many of us might have or might want to see if the error and it’s message is reported by the application or if some custom error and its message match with the one we added ourselves.

Checking for the same might spread over multiple lines since we need to store the exception occurring for the provided code and then check it using assert_match.

Let’s see it working ourselves by creating a new test file touch test/models/example_test.rb Add the following code to the file and run it using rails test test/models/example_test.rb -

Before

class ExampleTest < ActiveSupport::TestCase
  def test_exception
    error = assert_raises(NoMethodError) do
      Date.now
    end
    assert_match(/undefined method `now' for Date:Class/i, error.message)
  end
end

After

After this change now it is possible to do the above thing in a much cleaner way without having to store it in a variable.

class ExampleTest < ActiveSupport::TestCase
  def test_exception
    assert_raises(NoMethodError, match: /undefined method `now' for Date:Class/i) do
      Date.now
    end
  end
end

Summary

Due to this change made in Rails 7, now we can check for the exception and it’s message using just assert_raises instead of having to use both assert_raises and assert_match for doing the same.

Need help on your Ruby on Rails or React project?

Join Our Newsletter