thoughtbot--shoulda-matchers/lib/shoulda/matchers/active_model/validation_matcher.rb

97 lines
2.2 KiB
Ruby
Raw Normal View History

2010-12-15 22:34:19 +00:00
module Shoulda # :nodoc:
module Matchers
module ActiveModel # :nodoc:
2010-12-15 22:34:19 +00:00
class ValidationMatcher # :nodoc:
attr_reader :failure_message
alias failure_message_for_should failure_message
2010-12-15 22:34:19 +00:00
def initialize(attribute)
@attribute = attribute
@strict = false
end
2013-03-04 03:34:38 +00:00
def on(context)
@context = context
self
end
def strict
@strict = true
self
2010-12-15 22:34:19 +00:00
end
def failure_message_when_negated
@failure_message_when_negated || @failure_message
2010-12-15 22:34:19 +00:00
end
alias failure_message_for_should_not failure_message_when_negated
2010-12-15 22:34:19 +00:00
def matches?(subject)
@subject = subject
false
end
private
def allows_value_of(value, message = nil, &block)
allow = allow_value_matcher(value, message)
yield allow if block_given?
2010-12-15 22:34:19 +00:00
if allow.matches?(@subject)
@failure_message_when_negated = allow.failure_message_when_negated
2010-12-15 22:34:19 +00:00
true
else
@failure_message = allow.failure_message
2010-12-15 22:34:19 +00:00
false
end
end
def disallows_value_of(value, message = nil, &block)
disallow = disallow_value_matcher(value, message)
yield disallow if block_given?
2010-12-15 22:34:19 +00:00
if disallow.matches?(@subject)
@failure_message_when_negated = disallow.failure_message_when_negated
2010-12-15 22:34:19 +00:00
true
else
@failure_message = disallow.failure_message
false
2010-12-15 22:34:19 +00:00
end
end
def allow_value_matcher(value, message)
matcher = AllowValueMatcher.
new(value).
for(@attribute).
on(@context).
with_message(message)
if strict?
matcher.strict
else
matcher
end
end
def disallow_value_matcher(value, message)
matcher = DisallowValueMatcher.
new(value).
for(@attribute).
on(@context).
with_message(message)
if strict?
matcher.strict
else
matcher
end
end
def strict?
@strict
end
2010-12-15 22:34:19 +00:00
end
end
end
2012-03-23 14:50:45 +00:00
end