Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

RSpec extension: testing attr_protected and attr_accessible (See related posts)

Include this module in a spec or inside the Spec::Runner.configure block in the spec_helper.rb. Because i suck, should_not is not working as expected. Usage:

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


You need to create an account or log in to post comments to this site.


Click here to browse all 4858 code snippets

Related Posts