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.