Added only_integer option to ValidateNumericalityOfMatcher
This commit is contained in:
parent
0f1960bc46
commit
4131030437
|
@ -7,15 +7,23 @@ module Shoulda # :nodoc:
|
|||
# * <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
|
||||
#
|
||||
# Example:
|
||||
# it { should validate_numericality_of(:age) }
|
||||
# Examples:
|
||||
# it { should validate_numericality_of(:price) }
|
||||
# it { should validate_numericality_of(:age).only_integer }
|
||||
#
|
||||
def validate_numericality_of(attr)
|
||||
ValidateNumericalityOfMatcher.new(attr)
|
||||
end
|
||||
|
||||
class ValidateNumericalityOfMatcher < ValidationMatcher # :nodoc:
|
||||
|
||||
def only_integer
|
||||
@only_integer = true
|
||||
self
|
||||
end
|
||||
|
||||
def with_message(message)
|
||||
if message
|
||||
@expected_message = message
|
||||
|
@ -25,17 +33,30 @@ module Shoulda # :nodoc:
|
|||
|
||||
def matches?(subject)
|
||||
super(subject)
|
||||
disallows_value_of('abcd', expected_message)
|
||||
disallows_double_if_only_integer &&
|
||||
disallows_text
|
||||
end
|
||||
|
||||
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
|
||||
|
||||
private
|
||||
|
||||
def expected_message
|
||||
@expected_message || :not_a_number
|
||||
def disallows_double_if_only_integer
|
||||
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
|
||||
|
|
|
@ -19,6 +19,19 @@ describe Shoulda::Matchers::ActiveModel::ValidateNumericalityOfMatcher do
|
|||
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
|
||||
before do
|
||||
define_model :example, :attr => :string do
|
||||
|
|
Loading…
Reference in New Issue