diff --git a/lib/shoulda/active_record_helpers.rb b/lib/shoulda/active_record_helpers.rb index a95ec725..381a33fc 100644 --- a/lib/shoulda/active_record_helpers.rb +++ b/lib/shoulda/active_record_helpers.rb @@ -129,6 +129,28 @@ module ThoughtBot # :nodoc: end end + # Ensures that the attribute cannot be changed once the record has been created. + # Requires an existing record. + # + # should_have_readonly_attributes :password, :admin_flag + # + def should_have_readonly_attributes(*attributes) + get_options!(attributes) + klass = model_class + + attributes.each do |attribute| + attribute = attribute.to_sym + should "make #{attribute} read-only" do + readonly = klass.readonly_attributes || [] + + assert readonly.include?(attribute.to_s), + (readonly.empty? ? + "#{klass} attribute #{attribute} is not read-only" : + "#{klass} is making #{readonly.to_a.to_sentence} read-only, but not #{attribute}.") + end + end + end + # Ensures that the attribute cannot be set to the given values # Requires an existing record # diff --git a/test/rails_root/app/models/user.rb b/test/rails_root/app/models/user.rb index 310ea766..577c0c03 100644 --- a/test/rails_root/app/models/user.rb +++ b/test/rails_root/app/models/user.rb @@ -5,6 +5,7 @@ class User < ActiveRecord::Base has_one :address, :as => :addressable attr_protected :password + attr_readonly :name validates_format_of :email, :with => /\w*@\w*.com/ validates_length_of :email, :in => 1..100 diff --git a/test/unit/user_test.rb b/test/unit/user_test.rb index 9de19431..37a36c8b 100644 --- a/test/unit/user_test.rb +++ b/test/unit/user_test.rb @@ -27,4 +27,6 @@ class UserTest < Test::Unit::TestCase should_ensure_length_is :ssn, 9, :message => "Social Security Number is not the right length" should_only_allow_numeric_values_for :ssn + + should_have_readonly_attributes :name end