Created
February 22, 2012 18:08
-
-
Save obie/1886393 to your computer and use it in GitHub Desktop.
Example of using an anonymous class to build an RSpec custom Matcher
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
RSpec::Matchers also has a .define that will take care of the config stuff for you. Throw it in spec/support like so:
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.