Skip to content

Instantly share code, notes, and snippets.

@macedo
Created July 17, 2012 13:39
Show Gist options
  • Save macedo/3129447 to your computer and use it in GitHub Desktop.
Save macedo/3129447 to your computer and use it in GitHub Desktop.
RSpec matcher to test associations
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