Created
July 17, 2012 13:39
-
-
Save macedo/3129447 to your computer and use it in GitHub Desktop.
RSpec matcher to test associations
This file contains 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
RSpec::Matchers.define :have_association do |association| | |
@association = association | |
match_for_should do |record| | |
@record = record | |
matches_against?(true) | |
end | |
match_for_should_not do |record| | |
@record = record | |
matches_against?(false) | |
end | |
def matches_against?(compare) | |
raise "The have_association matcher requires an association and attribute; use subject.should have_association(:association).on(:attribute)" unless @association && @attribute | |
return (false == compare) unless (attribute = @record.class.reflect_on_association(@attribute.to_sym)) | |
(attribute.macro == @association.to_sym) == compare | |
end | |
chain :on do |attribute| | |
@attribute = attribute | |
end | |
failure_message_for_should do |actual| | |
"expect to have_association #{@association.inspect} on #{@attribut.inspect}" | |
end | |
failure_message_for_should_not do |actual| | |
"expect to not have_association #{@association.inspect} on #{@attribute.inspect}" | |
end | |
description do | |
"have association #{association.inspect} on #{@attribute.inspect}" | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment