Create a gist now

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Show comment
Hide comment
@myronmarston

myronmarston Feb 13, 2018

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.

Owner

myronmarston commented Feb 13, 2018

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

This comment has been minimized.

Show comment
Hide comment
@tcopeland

tcopeland Feb 13, 2018

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

tcopeland commented Feb 13, 2018

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