Skip to Content

Rspec - Negated matcher

Posted on

You can use RSpec::Matchers.define_negated_matcher to define a negated version of an existing matcher, to create a matcher with better name in your case.

For example:

RSpec::Matchers.define_negated_matcher :an_array_excluding, :include

RSpec.describe "A negated matcher" do
  let(:list) { 1.upto(10).to_a }

  it "can be used in a composed matcher expression" do
    expect { list.delete(5) }.to change { list }.to(an_array_excluding 5)
  end

  it "provides a good failure message based on the name" do
    # deliberate failure
    expect { list.delete(1) }.to change { list }.to(an_array_excluding 5)
  end
end

Reference:

comments powered by Disqus