Skip to content

Instantly share code, notes, and snippets.

@jasonroelofs
Created April 20, 2010 15:13
Show Gist options
  • Save jasonroelofs/372605 to your computer and use it in GitHub Desktop.
Save jasonroelofs/372605 to your computer and use it in GitHub Desktop.
# Finds all setter methods for the object,
# builds a new object with these methods set to an arbitrary value,
# checks if the given attrs are able to be mass assigned and all others are not,
# and finally returns true if there are no failures.
#
# (modified from: http://chrisconley.posterous.com/using-rspec-to-test-attraccessible)
Spec::Matchers.define :only_mass_assign_accessible_attributes do |*attrs|
match do |object|
@attrs = attrs
setters = object.methods.map{|m| m if m.match(/[a-z].*\=$/)}.compact
getters = setters.map{|s| s.gsub('=', '').to_sym}
accessible = object.class.accessible_attributes || []
@shouldnt, @should, @found = [], [], []
getters.each do |getter|
g = getter.to_s
if accessible.include?(g)
if attrs.include?(getter)
@should << g
else
@shouldnt << g
end
@found << getter
end
end
@shouldnt.length == 0 && @found.length == @attrs.length
end
failure_message_for_should do |actual|
str = ""
str += "The accessible attributes did not match. Expected #{@attrs.to_yaml} but got #{@found.to_yaml}"
str
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment