Read more

RSpec: Define negated matcher

Julian
December 15, 2021Software engineer at makandra GmbH

You can use RSpec::Matchers.define_negated_matcher to define a negated version of an existing matcher.

Illustration online protection

Rails professionals since 2007

Our laser focus on a single technology has made us a leader in this space. Need help?

  • We build a solid first version of your product
  • We train your development team
  • We rescue your project in trouble
Read more Show archive.org snapshot

This is particularly useful in composed matcher expressions or to create more expressive and meaningful matchers.

Examples

RSpec::Matchers.define_negated_matcher :not_change, :change

describe 'A negated matcher' do
  it 'can be used to chain negated changes' do
    expect { subject.maybe_change(object) }
      .to not_change(object, :attr_1)
      .and not_change(contract, :attr_2)
  end
end
RSpec::Matchers.define_negated_matcher :an_array_excluding, :include

describe 'A negated matcher' do
  it 'can be used in a composed matcher expression' do
    expect { list.delete(5) }.to change { list }.to(an_array_excluding(5))
  end
end
RSpec::Matchers.define_negated_matcher :exclude, :include

describe 'A negated matcher' do
  it 'can be used for creating more expressive and meaningful matchers' do
    expect(list.difference([5])).to exclude(5)
  end
end
Posted by Julian to makandra dev (2021-12-15 15:16)