Created
June 8, 2009 19:17
-
-
Save chrisconley/126007 to your computer and use it in GitHub Desktop.
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
# 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 |
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
class User < ActiveRecord::Base | |
has_many :orders | |
attr_accessible :email, :password, :password_confirmation | |
end |
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
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