thoughtbot--shoulda-matchers/lib/shoulda/matchers/active_model/validate_confirmation_of_ma...

66 lines
1.6 KiB
Ruby
Raw Normal View History

2011-10-23 13:41:37 +00:00
module Shoulda # :nodoc:
module Matchers
module ActiveModel # :nodoc:
# Ensures that the model's attribute matches confirmation
#
# Example:
# it { should validate_confirmation_of(:password) }
#
def validate_confirmation_of(attr)
ValidateConfirmationOfMatcher.new(attr)
end
class ValidateConfirmationOfMatcher < ValidationMatcher # :nodoc:
include Helpers
def initialize(attribute)
@attribute = attribute
@confirmation = "#{attribute}_confirmation"
end
def with_message(message)
@message = message if message
self
end
def description
"require #{@confirmation} to match #{@attribute}"
2011-10-23 13:41:37 +00:00
end
def matches?(subject)
super(subject)
@message ||= :confirmation
disallows_different_value &&
allows_same_value &&
allows_missing_confirmation
end
private
def disallows_different_value
2012-12-20 05:04:27 +00:00
set_confirmation('some value')
disallows_value_of('different value', @message)
2011-10-23 13:41:37 +00:00
end
def allows_same_value
2012-12-20 05:04:27 +00:00
set_confirmation('same value')
allows_value_of('same value', @message)
2011-10-23 13:41:37 +00:00
end
def allows_missing_confirmation
set_confirmation(nil)
2012-12-20 05:04:27 +00:00
allows_value_of('any value', @message)
2011-10-23 13:41:37 +00:00
end
def set_confirmation(val)
setter = :"#{@confirmation}="
2012-12-20 05:04:27 +00:00
if @subject.respond_to?(setter)
@subject.send(setter, val)
end
2011-10-23 13:41:37 +00:00
end
end
end
end
end