1
0
Fork 0
mirror of https://github.com/thoughtbot/shoulda-matchers.git synced 2022-11-09 12:01:38 -05:00

Added only_integer option to ValidateNumericalityOfMatcher

This commit is contained in:
Tomas Mattia 2011-10-27 00:21:06 -02:00 committed by Gabe Berke-Williams
parent 0f1960bc46
commit 4131030437
2 changed files with 40 additions and 6 deletions

View file

@ -7,15 +7,23 @@ module Shoulda # :nodoc:
# * <tt>with_message</tt> - value the test expects to find in # * <tt>with_message</tt> - value the test expects to find in
# <tt>errors.on(:attribute)</tt>. Regexp or string. Defaults to the # <tt>errors.on(:attribute)</tt>. Regexp or string. Defaults to the
# translation for <tt>:not_a_number</tt>. # translation for <tt>:not_a_number</tt>.
# * <tt>only_integer</tt> - allows only integer values
# #
# Example: # Examples:
# it { should validate_numericality_of(:age) } # it { should validate_numericality_of(:price) }
# it { should validate_numericality_of(:age).only_integer }
# #
def validate_numericality_of(attr) def validate_numericality_of(attr)
ValidateNumericalityOfMatcher.new(attr) ValidateNumericalityOfMatcher.new(attr)
end end
class ValidateNumericalityOfMatcher < ValidationMatcher # :nodoc: class ValidateNumericalityOfMatcher < ValidationMatcher # :nodoc:
def only_integer
@only_integer = true
self
end
def with_message(message) def with_message(message)
if message if message
@expected_message = message @expected_message = message
@ -25,17 +33,30 @@ module Shoulda # :nodoc:
def matches?(subject) def matches?(subject)
super(subject) super(subject)
disallows_value_of('abcd', expected_message) disallows_double_if_only_integer &&
disallows_text
end end
def description def description
"only allow numeric values for #{@attribute}" type = if @only_integer then "integer" else "numeric" end
description = "only allow #{type} values for #{@attribute}"
description
end end
private private
def expected_message def disallows_double_if_only_integer
@expected_message || :not_a_number if @only_integer
message = @expected_message || :not_an_integer
disallows_value_of(0.1, message) && disallows_value_of('0.1', message)
else
true
end
end
def disallows_text
message = @expected_message || :not_a_number
disallows_value_of('abcd', message)
end end
end end
end end

View file

@ -19,6 +19,19 @@ describe Shoulda::Matchers::ActiveModel::ValidateNumericalityOfMatcher do
end end
end end
context "a numeric attribute which must be integer" do
before do
define_model :example, :attr => :string do
validates_numericality_of :attr, { :only_integer => true }
end
@model = Example.new
end
it "should only allow integer values for that attribute" do
@model.should validate_numericality_of(:attr).only_integer
end
end
context "a numeric attribute with a custom validation message" do context "a numeric attribute with a custom validation message" do
before do before do
define_model :example, :attr => :string do define_model :example, :attr => :string do