2014-01-23 18:07:36 +00:00
|
|
|
module Shoulda
|
2010-12-15 22:34:19 +00:00
|
|
|
module Matchers
|
2014-01-23 18:07:36 +00:00
|
|
|
module ActiveRecord
|
|
|
|
# The `have_readonly_attribute` matcher tests usage of the
|
|
|
|
# `attr_readonly` macro.
|
|
|
|
#
|
|
|
|
# class User < ActiveRecord::Base
|
|
|
|
# attr_readonly :password
|
|
|
|
# end
|
|
|
|
#
|
|
|
|
# # RSpec
|
2016-06-16 00:00:51 +00:00
|
|
|
# RSpec.describe User, type: :model do
|
2014-01-23 18:07:36 +00:00
|
|
|
# it { should have_readonly_attribute(:password) }
|
|
|
|
# end
|
|
|
|
#
|
2015-09-30 19:15:23 +00:00
|
|
|
# # Minitest (Shoulda)
|
2014-01-23 18:07:36 +00:00
|
|
|
# class UserTest < ActiveSupport::TestCase
|
|
|
|
# should have_readonly_attribute(:password)
|
|
|
|
# end
|
2010-12-15 22:34:19 +00:00
|
|
|
#
|
2014-01-23 18:07:36 +00:00
|
|
|
# @return [HaveReadonlyAttributeMatcher]
|
2010-12-15 22:34:19 +00:00
|
|
|
#
|
|
|
|
def have_readonly_attribute(value)
|
|
|
|
HaveReadonlyAttributeMatcher.new(value)
|
|
|
|
end
|
|
|
|
|
2014-01-23 18:07:36 +00:00
|
|
|
# @private
|
|
|
|
class HaveReadonlyAttributeMatcher
|
2010-12-15 22:34:19 +00:00
|
|
|
def initialize(attribute)
|
|
|
|
@attribute = attribute.to_s
|
|
|
|
end
|
|
|
|
|
2013-12-24 11:24:27 +00:00
|
|
|
attr_reader :failure_message, :failure_message_when_negated
|
|
|
|
|
2010-12-15 22:34:19 +00:00
|
|
|
def matches?(subject)
|
|
|
|
@subject = subject
|
|
|
|
if readonly_attributes.include?(@attribute)
|
2013-12-24 11:24:27 +00:00
|
|
|
@failure_message_when_negated = "Did not expect #{@attribute} to be read-only"
|
2010-12-15 22:34:19 +00:00
|
|
|
true
|
|
|
|
else
|
|
|
|
if readonly_attributes.empty?
|
2013-12-24 11:24:27 +00:00
|
|
|
@failure_message = "#{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
|
2013-12-24 11:24:27 +00:00
|
|
|
@failure_message = "#{class_name} is making " <<
|
2011-02-23 16:13:59 +00:00
|
|
|
"#{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
|