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

74 lines
1.8 KiB
Ruby
Raw Normal View History

2010-12-15 22:34:19 +00:00
module Shoulda # :nodoc:
module Matchers
module ActiveModel # :nodoc:
# Ensure that the attribute is numeric.
2010-12-15 22:34:19 +00:00
#
# Options:
# * <tt>with_message</tt> - value the test expects to find in
# <tt>errors.on(:attribute)</tt>. Regexp or string. Defaults to the
# translation for <tt>:not_a_number</tt>.
# * <tt>only_integer</tt> - allows only integer values
2010-12-15 22:34:19 +00:00
#
# Examples:
# it { should validate_numericality_of(:price) }
# it { should validate_numericality_of(:age).only_integer }
2010-12-15 22:34:19 +00:00
#
def validate_numericality_of(attr)
ValidateNumericalityOfMatcher.new(attr)
end
class ValidateNumericalityOfMatcher < ValidationMatcher # :nodoc:
2012-04-24 22:00:26 +00:00
def initialize(attribute)
super(attribute)
@options = {}
end
def only_integer
2012-04-24 22:00:26 +00:00
@options[:only_integer] = true
self
end
2010-12-15 22:34:19 +00:00
def with_message(message)
if message
@expected_message = message
end
2010-12-15 22:34:19 +00:00
self
end
def matches?(subject)
super(subject)
2012-04-04 00:20:50 +00:00
disallows_non_integers? && disallows_text?
2010-12-15 22:34:19 +00:00
end
def description
2012-04-04 00:20:50 +00:00
"only allow #{allowed_type} values for #{@attribute}"
2010-12-15 22:34:19 +00:00
end
private
2012-04-04 00:20:50 +00:00
def allowed_type
2012-04-24 22:00:26 +00:00
if @options[:only_integer]
2012-04-04 00:20:50 +00:00
"integer"
else
"numeric"
end
end
def disallows_non_integers?
2012-04-24 22:00:26 +00:00
if @options[:only_integer]
message = @expected_message || :not_an_integer
2012-04-24 22:00:26 +00:00
disallows_value_of(0.1, message)
else
true
end
end
2012-04-04 00:20:50 +00:00
def disallows_text?
message = @expected_message || :not_a_number
disallows_value_of('abcd', message)
end
end
2010-12-15 22:34:19 +00:00
end
end
end