2010-12-15 22:34:19 +00:00
|
|
|
module Shoulda # :nodoc:
|
|
|
|
module Matchers
|
2011-05-06 11:51:12 +00:00
|
|
|
module ActiveModel # :nodoc:
|
2010-12-15 22:34:19 +00:00
|
|
|
|
|
|
|
# Ensures that the model is not valid if the given attribute is not
|
|
|
|
# present.
|
|
|
|
#
|
|
|
|
# Options:
|
|
|
|
# * <tt>with_message</tt> - value the test expects to find in
|
|
|
|
# <tt>errors.on(:attribute)</tt>. <tt>Regexp</tt> or <tt>String</tt>.
|
|
|
|
# Defaults to the translation for <tt>:blank</tt>.
|
|
|
|
#
|
|
|
|
# Examples:
|
|
|
|
# it { should validate_presence_of(:name) }
|
|
|
|
# it { should validate_presence_of(:name).
|
|
|
|
# with_message(/is not optional/) }
|
|
|
|
#
|
|
|
|
def validate_presence_of(attr)
|
|
|
|
ValidatePresenceOfMatcher.new(attr)
|
|
|
|
end
|
|
|
|
|
|
|
|
class ValidatePresenceOfMatcher < ValidationMatcher # :nodoc:
|
|
|
|
def with_message(message)
|
|
|
|
@expected_message = message if message
|
|
|
|
self
|
|
|
|
end
|
|
|
|
|
|
|
|
def matches?(subject)
|
|
|
|
super(subject)
|
|
|
|
@expected_message ||= :blank
|
|
|
|
disallows_value_of(blank_value, @expected_message)
|
2013-11-22 20:46:59 +00:00
|
|
|
rescue Shoulda::Matchers::ActiveModel::CouldNotClearAttribute => error
|
|
|
|
if @attribute == :password
|
|
|
|
raise Shoulda::Matchers::ActiveModel::CouldNotSetPasswordError.create(subject.class)
|
|
|
|
else
|
|
|
|
raise error
|
|
|
|
end
|
2010-12-15 22:34:19 +00:00
|
|
|
end
|
|
|
|
|
|
|
|
def description
|
|
|
|
"require #{@attribute} to be set"
|
|
|
|
end
|
|
|
|
|
|
|
|
private
|
|
|
|
|
|
|
|
def blank_value
|
|
|
|
if collection?
|
|
|
|
[]
|
|
|
|
else
|
|
|
|
nil
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
def collection?
|
2012-04-24 22:01:50 +00:00
|
|
|
if reflection
|
2010-12-15 22:34:19 +00:00
|
|
|
[:has_many, :has_and_belongs_to_many].include?(reflection.macro)
|
|
|
|
else
|
|
|
|
false
|
|
|
|
end
|
|
|
|
end
|
2012-04-24 22:01:50 +00:00
|
|
|
|
|
|
|
def reflection
|
|
|
|
@subject.class.respond_to?(:reflect_on_association) &&
|
|
|
|
@subject.class.reflect_on_association(@attribute)
|
|
|
|
end
|
2010-12-15 22:34:19 +00:00
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|