How to test with regular expressions using assert_match

Minitest comes with plenty of handy assertions. If the matching is a little fuzzy, assert_match can help.

Regexp tests

Sometimes, equality tests aren't as useful when we cannot do an exact match. What if we have a formatter that works with dates and we only care about the correct format instead of the values themselves?

We can test it using assert_match to match our test object against a regular expression:

class Message < ActiveRecord::Base
end

class Formatter
  def self.format_message(message)
    "#{message.created_at.strftime("%Y-%m-%d")}: #{message.text}"
  end
end

require "minitest/autorun"

class FormatterTest < Minitest::Test
  def setup
    message = Message.create!(text: "Hi")
  end

  def test_log
    result = Formatter.format_message(message)
    assert_match(/\d{4}-\d{2}-\d{2}: Hi/, result)
  end
end

This assertion will also come in handy when matching against response.body in controller tests.

Get the book

Get the one and only book on official Rails testing strategies with Minitest and Fixtures, from the author of Kamal Handbook.

Get the book