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 web development

Do you need DevOps-experts?

Your development team has a full backlog? No time for infrastructure architecture? Our DevOps team is ready to support you!

  • We build reliable cloud solutions with Infrastructure as code
  • We are experts in security, Linux and databases
  • We support your dev team to perform
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)