Skip to content

Instantly share code, notes, and snippets.

@obie
Created February 22, 2012 18:08
Show Gist options
  • Save obie/1886393 to your computer and use it in GitHub Desktop.
Save obie/1886393 to your computer and use it in GitHub Desktop.
Example of using an anonymous class to build an RSpec custom Matcher
def be_guest_member_of(expected)
Class.new do
def initialize(expected)
@expected = expected
end
def matches?(target)
@target = target
@target.memberships.where(role: "guest").map(&:network).include? @expected
end
def failure_message_for_should
"expected #{@target.inspect} to be a guest member of #{@expected.inspect}"
end
def failure_message_for_should_not
"expected #{@target.inspect} to not be a guest member of #{@expected.inspect}"
end
end.new(expected)
end
# usage example
user1.should be_guest_member_of network2
user1.should_not be_guest_member_of network1
@supaspoida
Copy link

RSpec::Matchers also has a .define that will take care of the config stuff for you. Throw it in spec/support like so:

RSpec::Matchers.define :be_guest_member_of do |expected|
  match do |target|
    target.memberships.where(role: "guest").map(&:network).include? expected
  end

  failure_message_for_should do |target|
    "expected #{target.inspect} to be a guest member of #{expected.inspect}"
  end

  failure_message_for_should_not do |target|
    "expected #{target.inspect} to not be a guest member of #{expected.inspect}"
  end
end

I would argue that this is the cleanest way to go, but make no claims regarding performance.

I do think in this case that reaching through so many associations like that is an indicator that the design should change to improve the tests though.

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