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
|
|
|
# Ensure that the attribute is numeric
|
|
|
|
#
|
|
|
|
# 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>.
|
2011-10-27 02:21:06 +00:00
|
|
|
# * <tt>only_integer</tt> - allows only integer values
|
2010-12-15 22:34:19 +00:00
|
|
|
#
|
2011-10-27 02:21:06 +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
|
2011-10-27 02:21:06 +00:00
|
|
|
|
|
|
|
def only_integer
|
2012-04-24 22:00:26 +00:00
|
|
|
@options[:only_integer] = true
|
2011-10-27 02:21:06 +00:00
|
|
|
self
|
|
|
|
end
|
|
|
|
|
2010-12-15 22:34:19 +00:00
|
|
|
def with_message(message)
|
2012-03-30 14:36:55 +00:00
|
|
|
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
|
|
|
|
|
2012-03-30 14:36:55 +00:00
|
|
|
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]
|
2011-10-27 02:21:06 +00:00
|
|
|
message = @expected_message || :not_an_integer
|
2012-04-24 22:00:26 +00:00
|
|
|
disallows_value_of(0.1, message)
|
2011-10-27 02:21:06 +00:00
|
|
|
else
|
|
|
|
true
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2012-04-04 00:20:50 +00:00
|
|
|
def disallows_text?
|
2011-10-27 02:21:06 +00:00
|
|
|
message = @expected_message || :not_a_number
|
|
|
|
disallows_value_of('abcd', message)
|
2012-03-30 14:36:55 +00:00
|
|
|
end
|
|
|
|
end
|
2010-12-15 22:34:19 +00:00
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|