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

87 lines
2.3 KiB
Ruby
Raw Normal View History

2010-12-15 17:34:19 -05:00
module Shoulda # :nodoc:
module Matchers
module ActiveModel # :nodoc:
# Ensure that the attribute is numeric.
2010-12-15 17:34:19 -05: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 17:34:19 -05:00
#
# Examples:
# it { should validate_numericality_of(:price) }
# it { should validate_numericality_of(:age).only_integer }
2010-12-15 17:34:19 -05:00
#
def validate_numericality_of(attr)
ValidateNumericalityOfMatcher.new(attr)
end
class ValidateNumericalityOfMatcher
2012-04-24 18:00:26 -04:00
def initialize(attribute)
@attribute = attribute
2012-04-24 18:00:26 -04:00
@options = {}
@submatchers = []
add_disallow_value_matcher
2012-04-24 18:00:26 -04:00
end
def only_integer
only_integer_matcher = OnlyIntegerMatcher.new(@attribute)
add_submatcher(only_integer_matcher)
self
end
2010-12-15 17:34:19 -05:00
def with_message(message)
@expected_message = message
2010-12-15 17:34:19 -05:00
self
end
def matches?(subject)
@subject = subject
set_expected_message_on_submatchers
submatchers_match?
2010-12-15 17:34:19 -05:00
end
def description
"only allow #{allowed_types} values for #{@attribute}"
end
def failure_message
@disallow_value_matcher.failure_message
2010-12-15 17:34:19 -05:00
end
private
def add_disallow_value_matcher
@disallow_value_matcher = DisallowValueMatcher.new('abcd').for(@attribute)
add_submatcher(@disallow_value_matcher)
2012-04-03 20:20:50 -04:00
end
def add_submatcher(submatcher)
@submatchers << submatcher
end
def set_expected_message_on_submatchers
message = @expected_message || :not_a_number
@submatchers.each { |matcher| matcher.with_message(message) }
end
def submatchers_match?
@submatchers.all? { |matcher| matcher.matches?(@subject) }
end
def allowed_types
allowed = ["numeric"] + submatcher_allowed_types
allowed.join(", ")
end
def submatcher_allowed_types
@submatchers.map(&:allowed_types).reject { |type| type.empty? }
end
end
2010-12-15 17:34:19 -05:00
end
end
end