If you haven’t written Ruby tests using Minitest in a while, you might have missed the addition of the assert_pattern assertion (available in Ruby 3.0 and higher). Right now, it’s my absolute favorite assertion when I need to validate a complex object-like an array or a hash-in a single go.
Of course, there is one limitation when checking hashes: keys can only be symbols. So if you want to validate JSON, you’ll need to transform its keys from strings to symbols first.
require 'json'
require 'minitest'
class ExampleTest < Minitest::Test
def test_example_array_assert_pattern
xs = Array.new(3) { rand(100) }
assert_pattern { xs => [Integer, Integer, Integer] }
end
def test_example_hash_assert_pattern
h = JSON.parse(
'{"id":1,"name":"Artem","busy":true,"langs":["Ruby","Rust"]}'
)
h = h.transform_keys(&:to_sym)
lang = 'Ruby'
assert_pattern do
h => {
id: Integer,
name: String,
busy: TrueClass | FalseClass,
langs: [^lang, *]
}
end
end
end
Minitest.run # Explicitly running tests in IRB
Have you had any experience using assert_pattern? What are your favorite Minitest assertions to use in projects?