Created
August 29, 2010 00:38
-
-
Save rafaelp/555770 to your computer and use it in GitHub Desktop.
RSpec extension: matcher to test attr_protected
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
# Refactored from: http://snippets.dzone.com/posts/show/4712 | |
Spec::Matchers.define :protect_attributes do |*attributes| | |
match do |target| | |
calculate_protected_methods(target) | |
perform_check(attributes) | |
end | |
failure_message_for_should do |target| | |
"expected #{@failed_attribute} to be protected" | |
end | |
failure_message_for_should_not do |target| | |
"expected #{@failed_attribute} to not be protected" | |
end | |
description do | |
"protect attributes #{attributes.join(", ")}" | |
end | |
def calculate_protected_methods(target) | |
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.to_a.map!(&:to_sym) if protekted | |
@protected = all - accessible.to_a.map!(&:to_sym) if @accessible | |
@accessible = (all - @protected).to_a | |
end | |
def perform_check(attributes) | |
failed_attributes = (attributes & @accessible) | |
@failed_attribute = failed_attributes.first | |
failed_attributes.empty? | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment