Skip to main content
Published in Engineering Insights

RSpec Negated Matchers

RSpec Negated Matchers
Table of contents
  1. Problem
  2. Why does RSpec refuse not_to with and?
  3. Solution
  4. Where do you define a negated matcher?
  5. What should you name a negated matcher: not_change or avoid_changing?
  6. Should you use not_change or change.by(0)?
  7. Which negated change forms does RSpec support?
  8. Does the block run once, and what about or?
  9. How do you negate have_received and raise_error?
  10. When is a negated matcher the wrong tool?
  11. Which RSpec versions does this apply to?

Problem#

We want to test that when we call our Ruby method, one result does occur while another result does not occur. Specifically, we want to test that an Event is created but that an EventPayload is not created. Using RSpec, we have this so far:

Ruby
it "creates an event without an associated payload" do
  expect { service.create_event! }.to change { Event.count }.by(1)
  expect { service.create_event! }.not_to change { EventPayload.count }
end

This is ok, but we'd like to run both expectations on a single method call.

We know that RSpec has and which can help us make compound expectations, but this falls apart when we want to make one positive assertion and one negative assertion. We could try this:

Ruby
it "creates an event without an associated payload" do
  expect { service.create_event! }
    .not_to change { EventPayload.count }
    .and change { Event.count }.by(1)
end

But no joy:

Ruby
NotImplementedError: expect(...).not_to matcher.and matcher` is not supported, since it creates a bit of an ambiguity.

Why does RSpec refuse not_to with and?#

RSpec raises NotImplementedError on purpose when not_to meets a compound matcher. The compound matcher source in rspec-expectations 3.13.6 says the form "creates a bit of an ambiguity." The same error covers or. The message fills in whichever word joined the matchers. The way out it names is the one this post uses: negated matchers under to.

Read the failing line aloud and the problem shows. Putting not_to in front of "change payloads and change events" has two fair readings: "not both" or "neither." Take the result this post wants, one new Event and no new EventPayload. Only one count changes. "Not both" would pass that run, because the two counts did not both change. "Neither" would fail it, because the Event count went up by one. The same run gets two verdicts. RSpec does not pick a reading, so it raises an error instead.

The error comes from where not_to lands. RSpec calls the matcher's does_not_match? method when it has one, and the compound matcher's version of that method only raises this error.

The full message ends with the fix. Define negated versions of the matchers with RSpec::Matchers.define_negated_matcher, then use expect(...).to matcher.and matcher.

A negated matcher turns the negative assertion into a positive one, so and works again.

Solution#

How can we chain two expectations together with and if one is a "not" condition? RSpec allows us to define a negated matcher:

Ruby
RSpec::Matchers.define_negated_matcher :not_change, :change

Which allows us to then write this:

Ruby
it "creates an event without an associated payload" do
  expect { service.create_event! }
    .to change { Event.count }.by(1)
    .and(not_change { EventPayload.count })
end

And we can flip the order if we choose:

Ruby
it "creates an event without an associated payload" do
  expect { service.create_event! }
    .to not_change { EventPayload.count }
    .and change { Event.count }.by(1)
end

Fun!

Where do you define a negated matcher?#

Define it once in a file that loads before your specs, such as spec/spec_helper.rb. A project set up with rspec --init loads that file through the --require spec_helper line in .rspec. Since rspec-expectations 3.6.0, you can also call define_negated_matcher inside one example group. Groups outside it cannot see it, but groups nested inside it can.

The post introduced the idea in one sentence: "RSpec allows us to define a negated matcher." The scoped version of its example puts that definition inside the group:

Ruby
RSpec.describe "event creation" do
  define_negated_matcher :not_change, :change

  it "creates an event without an associated payload" do
    expect { service.create_event! }
      .to change { Event.count }.by(1)
      .and(not_change { EventPayload.count })
  end
end

The first argument is the new name. The second is the matcher it negates. It works with other matchers too. RSpec's own source comments define exclude as the negation of include. The define negated matcher page calls it "particularly useful in composed matcher expressions," such as change { list }.to(an_array_excluding 5).

RSpec also rewrites the matcher's description from the new name. On that page, a failing example reads "expected list to have changed to an array excluding 5, but is now [2, 3, 4, 5, 6, 7, 8, 9, 10]." You can pass an optional block to define_negated_matcher to write that text yourself. The block receives the original description or failure message.

What should you name a negated matcher: not_change or avoid_changing?#

Either name works, because the name does not change what the matcher checks. RSpec's own documentation leans toward a positive name. A comment in the rspec-expectations matchers file says a not_ prefix can give confusing failure messages. It adds: "We've found it works best to find a more positive name for the negated form, such as avoid_changing rather than not_change."

For change itself, the name makes no difference to the failure text. On 3.13.6, a failing to not_change { EventPayload.count } and a failing to avoid_changing { EventPayload.count } print the same line. It reads "expected `EventPayload.count` not to have changed, but did change from 0 to 1." A plain not_to change prints it too.

So pick the name your readers will parse fastest. A Gnar engineering post on unit tests sets the bar for specs: "The unit tests should therefore demonstrate how to use the class for newcomers." For a team that reads change every day, not_change is clear at a glance. For newcomers, avoid_changing reads as plain English.

Should you use not_change or change.by(0)?#

Both work for a count that must stay the same, such as EventPayload.count. change { }.by(0) subtracts the before value from the after value, so after minus before must equal 0, as it does for numbers. not_change compares the before and after values instead. On 3.13.6, by(0) on a string raises NoMethodError, while not_change on the same string passes. On an unchanged array, by(0) fails with "was changed by []."

not_change also catches a value changed in place. The change matcher counts a value as changed when before and after are unequal or their hash values differ. A comment in its source says the hash check covers a block that "returns the exact same object, but it has been mutated." So expect { list << 1 }.to not_change { list } fails with "did change from [] to [1]."

FormPasses whenValues it handles
change { x }.by(0)After minus before equals 0Numbers. Arrays and strings should use not_change
not_change { x }The before and after values matchNumbers, strings and other objects
not_to change { x }Same as not_changeSame, but it cannot be chained with and or or

Which negated change forms does RSpec support?#

On rspec-expectations 3.13.6, a negated change supports two forms: bare, and with .from(x). Adding .by, .by_at_least, .by_at_most or .to raises NotImplementedError. A negated matcher such as not_change has the same limits, because it runs the negated form of change.

Added to not_to change { x }Result on 3.13.6
NothingPasses when x stays the same
.from(0)Passes when x starts at 0 and stays there
.to(1)NotImplementedError
.by(1)NotImplementedError
.by_at_least(1)NotImplementedError
.by_at_most(1)NotImplementedError

To check that two values both stay the same, chain two negated matchers under to. A call that should create neither record reads to not_change { Event.count }.and not_change { EventPayload.count }. Add another .and not_change for a third value.

The from form also checks the start value. If EventPayload.count starts at 0, not_to change { EventPayload.count }.from(5) fails with "expected `EventPayload.count` to have initially been 5, but was 0." That puts the start value in the spec itself. The Gnar post on unit tests argues for tests as documentation: "Human-readable comments rot, but CI failures are forever, or at least final."

Does the block run once, and what about or?#

A compound block expectation runs the code under test once, whether the matchers are joined with and or with or. The compound matcher source nests one matcher inside the other. Its comment says this is "necessary so that the expect block is only executed once." The compound expectations page also shows & and | as aliases for and and or.

Negated matchers work with or as well. expect { n += 1 }.to not_change { n }.or change { n }.by(1) passes, because the second matcher holds.

That single run is what the post was after: "This is ok, but we'd like to run both expectations on a single method call." With and, service.create_event! runs one time.

A raise_error matcher can join a change matcher in the same expectation. The change matcher still counts what the code did before it raised:

Ruby
it "counts the log entry written before the error" do
  log = []
  expect {
    log << "started"
    raise ArgumentError, "bad input"
  }.to raise_error(ArgumentError, "bad input")
    .and change { log.size }.by(1)
end

Two matchers that both expect a call stack jump, such as raise_error and throw_symbol, cannot share an expectation. RSpec raises ArgumentError for that pair. Since 3.13.2, mixing a value matcher such as eq with a block matcher such as change raises an error too.

How do you negate have_received and raise_error?#

You negate both with not_to, and each one has a limit worth knowing. On a spy, expect(notifier).not_to have_received(:ping) works. Adding a count such as exactly, at_least or once raises an error such as "can't use exactly when negative." expect { }.not_to raise_error(SomeError) works, but RSpec warns that it "risks false positives."

Argument checks still work on the negated form. If notifier.ping(:a) ran, expect(notifier).not_to have_received(:ping).with(:b) passes, because ping never received :b.

The raise_error warning explains itself: "literally any other error would cause the expectation to pass." It suggests expect { }.not_to raise_error with no arguments, or expect { }.to raise_error(DifferentSpecificErrorClass). The on_potential_false_positives setting accepts :warn, the default, :raise or :nothing.

When is a negated matcher the wrong tool?#

A negated matcher is the wrong tool when the opposite of a matcher has more than one meaning. The card on negated matchers in makandra dev, a public deck on makandracards.com, says to negate only "atomic" matchers with an unambiguous inversion. Its example: have_radio_button(label) can be negated, but have_active_radio_button(label) should not be.

The card explains why. The inverse could mean the button exists but is not active. It could also mean there is no button with that label at all. The card's fix is an attribute: have_radio_button(label, active: true). When no attribute fits, write a custom matcher with RSpec's matcher DSL. Its match_when_negated block is for "when the positive and negative forms require different handling." RSpec calls that "rarely necessary." Its failure_message_when_negated block sets the text a reader sees on failure.

Write that text for the next reader. A Gnar engineering post on temporary state in tests names that reader: "we want to be clear to readers who may not have perused the Rails documentation (nor have encyclopedic knowledge of it)."

Which RSpec versions does this apply to?#

Every rspec-expectations behavior above holds on 3.13.6, the latest stable release on RubyGems, published November 6, 2026. Most of it is much older. The have_received results come from rspec-mocks 3.13.9. define_negated_matcher and compound block expectations both arrived in 3.1.0, in September 2014. The 4.0.0.beta1 prerelease still raises NotImplementedError for not_to with and.

VersionWhat changed
3.1.0Added define_negated_matcher. Compound matchers started working with block matchers such as change.
3.6.0define_negated_matcher can be called inside one example group.
3.12.1Keyword arguments pass through to negated matchers.
3.13.2Mixing block and value matchers in a compound expectation raises an error.
4.0.0.beta1Prerelease. Passing nil to raise_error raises ArgumentError. Negated change errors get new wording.

A negated matcher joined with and has been available since 3.1.0. On 3.13.6, expect { }.not_to raise_error(nil) passes with a warning. On 4.0.0.beta1, passing nil to raise_error raises ArgumentError. Check negated raise_error specs before that upgrade. The same prerelease also drops support for Ruby versions before 3.0.

Learn more about how The Gnar builds Ruby on Rails applications.

Frequently asked questions

Why combine these expectations?

The goal is to test both outcomes from a single call to service.create_event!. Separate expectations run that call twice.

How do I define not_change?

Use RSpec::Matchers.define_negated_matcher :not_change, :change. This defines a negated version of the change matcher.

Can the negative expectation come first?

Yes. The example starts with .to not_change { EventPayload.count } and follows it with .and change { Event.count }.by(1).

Why does not_to with and raise NotImplementedError?

RSpec rejects not_to with a compound matcher on purpose. Its message says the form creates a bit of an ambiguity. The same error appears for or. The message tells you to define negated matchers with define_negated_matcher and use to instead.

Is to_not the same as not_to in RSpec?

Yes. to_not is an alias of not_to on the expectation target, so both run the same code. RSpec's change matcher documentation shows both forms. Pick one and use it across the suite.

Can I use not_to change with by?

No. On rspec-expectations 3.13.6, a negated change with by, by_at_least, by_at_most or to raises NotImplementedError. Use change.by(0) or not_change for a count that must stay the same. A negated change with from(x) is supported.

Can I check that two things did not change in one expectation?

Yes. Chain two negated matchers under to, as in to not_change { Event.count }.and not_change { EventPayload.count }. Add more with and. Each value is read before and after one run of the block.

Does the block run once when I chain matchers with and?

Yes. RSpec nests the matchers so the code under test runs one time, for and and for or. That is why chaining beats two separate expectations, which would call service.create_event! twice.

Stay In The Loop

Never miss an update. Get the latest blogs, webinars, and expert insights straight to your inbox from The Gnar.