class User < ActiveRecord::Base # either attr_accessible :username, :full_name # or attr_protected :admin, :foo end # ... it "should protect admin and foo" do @user.should protect_attributes(:admin, :foo) end
Here goes:
module CustomExpectations class ProtectAttributes def initialize(*attributes) @attributes = attributes end def matches?(target) @target = target calculate_protected_methods perform_check end def failure_message "expected #{@failed_attribute} to be protected" end def negative_failure_message "expected #{@failed_attribute} to not be protected" end private def calculate_protected_methods read = proc {|var| @target.instance_eval { self.class.read_inheritable_attribute(var) } } accessible = read.call("attr_accessible") protekted = read.call("attr_protected") all = @target.class.column_names.map(&:to_sym) @protected = [] @protected << protekted if protekted @protected << (all - accessible) if accessible @protected.flatten! @accessible = all - @protected end def perform_check failed_attributes = (@attributes & @accessible) @failed_attribute = failed_attributes.first failed_attributes.empty? end end def protect_attributes(attributes) ProtectAttributes.new(attributes) end def protect_attribute(attribute) ProtectAttributes.new(*[attribute]) end end