thoughtbot--shoulda-matchers/lib/shoulda/matchers/active_record/have_readonly_attribute_mat...

56 lines
1.5 KiB
Ruby
Raw Normal View History

2010-12-15 22:34:19 +00:00
module Shoulda # :nodoc:
module Matchers
module ActiveRecord # :nodoc:
# Ensures that the attribute cannot be changed once the record has been
# created.
#
# it { should have_readonly_attribute(:password) }
2010-12-15 22:34:19 +00:00
#
def have_readonly_attribute(value)
HaveReadonlyAttributeMatcher.new(value)
end
class HaveReadonlyAttributeMatcher # :nodoc:
def initialize(attribute)
@attribute = attribute.to_s
end
attr_reader :failure_message_for_should, :failure_message_for_should_not
2012-03-30 15:22:31 +00:00
2010-12-15 22:34:19 +00:00
def matches?(subject)
@subject = subject
if readonly_attributes.include?(@attribute)
@failure_message_for_should_not = "Did not expect #{@attribute} to be read-only"
2010-12-15 22:34:19 +00:00
true
else
if readonly_attributes.empty?
@failure_message_for_should = "#{class_name} attribute #{@attribute} " <<
2012-12-20 05:04:27 +00:00
'is not read-only'
2010-12-15 22:34:19 +00:00
else
@failure_message_for_should = "#{class_name} is making " <<
"#{readonly_attributes.to_a.to_sentence} " <<
2010-12-15 22:34:19 +00:00
"read-only, but not #{@attribute}."
end
false
end
end
def description
"make #{@attribute} read-only"
end
private
def readonly_attributes
@readonly_attributes ||= (@subject.class.readonly_attributes || [])
end
def class_name
@subject.class.name
end
end
end
end
end