TIL: an_array_starting_with matcher

epigene

Augusts Bautra

Posted on June 13, 2024

TIL: an_array_starting_with matcher

Today I was working with generating excel files for export and had some trouble with tests - the generator (or maybe parser?) kept adding a random number of empty cells after the relevant data, making assertions fail.

Luckily, we can define our own matcher to ignore these irrelevant details. Also makes the spec read better. :)

# spec/support/matchers/array_starting_with_matcher.rb
RSpec::Matchers.define :an_array_starting_with do |expected|
  match do |actual|
    actual.is_a?(Array) && actual.first == expected
  end
end

# then in specs
expect(
  [
    :a,
    [:b, nil, nil]
  ]
).to match(
  [
    :a,
    an_array_starting_with(:b)
  ]
)
Enter fullscreen mode Exit fullscreen mode
💖 💪 🙅 🚩
epigene
Augusts Bautra

Posted on June 13, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related