Skip to content

Instantly share code, notes, and snippets.

@myronmarston
Created February 13, 2018 05:47
Show Gist options
  • Save myronmarston/c619133188f9df451b820fa45b400959 to your computer and use it in GitHub Desktop.
Save myronmarston/c619133188f9df451b820fa45b400959 to your computer and use it in GitHub Desktop.
module IncrementAndDecrement
def increment(&block)
matcher = change(&block).by(1)
RSpec::Matchers::AliasedMatcher.new(matcher, lambda do |desc|
desc.gsub("changed", "incremented").gsub("change", "increment")
end)
end
def decrement(&block)
matcher = change(&block).by(-1)
RSpec::Matchers::AliasedMatcher.new(matcher, lambda do |desc|
desc.gsub("changed", "decremented").gsub("change", "decrement").gsub("-", "")
end)
end
end
RSpec.configure do |c|
c.include IncrementAndDecrement
end
@myronmarston
Copy link
Author

Technically, RSpec::Matchers::AliasedMatchers isn't part of RSpec's public API, so if you want to stick only with public APIs, you can do:

RSpec::Matchers.alias_matcher :increment, :change do |desc|
  desc.gsub("changed", "incremented").gsub("change", "increment")
end

RSpec::Matchers.alias_matcher :decrement, :change do |desc|
  desc.gsub("changed", "decremented").gsub("change", "decrement").gsub("-", "")
end

module IncrementAndDecrement
  def increment(&block)
    super(&block).by(1)
  end

  def decrement(&block)
    super(&block).by(-1)
  end
end

RSpec.configure do |c|
  c.include IncrementAndDecrement
end

RSpec::Matchers.alias_matcher is part of the public API, so you don't have to worry about private API breakages with this, but it's also more convoluted, so YMMV.

@tcopeland
Copy link

Brilliant! That's a big improvement, thank you Myron! Post updated.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment