Skip to content

Instantly share code, notes, and snippets.

@chrisconley
Created June 8, 2009 19:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chrisconley/126007 to your computer and use it in GitHub Desktop.
Save chrisconley/126007 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.
Spec::Matchers.define :only_mass_assign_accessible_attributes do |*attrs|
match do |object|
setters = object.methods.map{|m| m if m.match(/[a-z].*\=$/)}.compact
getters = setters.map{|s| s.gsub('=', '').to_sym}
params = {}
getters.each do |getter|
params[getter] = 'test'
end
record = object.class.new(params)
@shouldnt, @should = [], []
getters.each do |getter|
value = record.send(getter)
if value == 'test' && !attrs.include?(getter)
@shouldnt << getter.to_s
elsif value != 'test' && attrs.include?(getter)
@should << getter.to_s
end
end
@shouldnt.length > 0 && @should.length > 0 ? false : true
end
failure_message_for_should do |actual|
str = ""
str += "The following attributes were mass assigned even though they shouldn't have been: #{@shouldnt.to_yaml}" unless @shouldnt.empty?
str += "The following attributes were not mass assigned even though they should have been: #{@should.to_yaml}" unless @should.empty?
str
end
end
class User < ActiveRecord::Base
has_many :orders
attr_accessible :email, :password, :password_confirmation
end
describe User do
it {should only_mass_assign_accessible_attributes(:email, :password, :password_confirmation)}
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment