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 UI/UX Design

UI/UX Design by makandra brand

We make sure that your target audience has the best possible experience with your digital product. You get:

  • Design tailored to your audience
  • Proven processes customized to your needs
  • An expert team of experienced designers
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)