An RSpec matcher for increment and decrement

12 Feb 2018

I've got some specs that verify a row was removed by expecting Foo.count to be decremented:

expect do
  # some wonderful things
end.to change { Foo.count }.by(-1)

But change ... by(-1) seems a little wordy. This would be more expressive:

expect do
  # some wonderful things
end.to decrement { Foo.count }

And of course we'd want to be able to chain these, and to use increment in place of change ... by(1):

expect do
  # some wonderful things
end.to decrement { Foo.count }
   .and increment { Bar.count }

Update: I had fiddled around and come up with a not-so-great way to do this when Myron Marston pinged me with a much nicer technique using RSpec's alias_matcher API. Thanks Myron!