Skip to content

Instantly share code, notes, and snippets.

@macedo
Created July 17, 2012 12:51
Show Gist options
  • Save macedo/3129234 to your computer and use it in GitHub Desktop.
Save macedo/3129234 to your computer and use it in GitHub Desktop.
RSpec matcher to test nested attributes
RSpec::Matchers.define :accept_nested_attributes_for 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 accept_nested_attributes_for matcher requires an association; use subject.should accept_nested_attributes_for(:association)" unless @association
@record.class.instance_methods.include?("#{@association}_attributes=".to_sym) == compare
end
failure_message_for_should do |actual|
"expect to accept nested attributes for #{@association.inspect}"
end
failure_message_for_should_not do |actual|
"expect to reject nested_attributes for #{@association.inspect}"
end
description do
"accept nested attributes for #{@association.inspect}"
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment