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.

Table of contents

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.

Author
Josef Strzibny
Hello, I am Josef and I am on Rails since its 2.0 version. I always liked strong conventions and the Rails Omakase docrine. I am author of Kamal Handbook and Test Driving Rails. I think testing should be fun, not a chore.

© Test Driving Rails Blog