Permalink
Browse files

Add #strict option to validation matchers

* Allow verifying validates! and :strict => true
  • Loading branch information...
1 parent 025023d commit d9289fa5c7606873fdc60a780ed80a483854c19d @jferris jferris committed Sep 12, 2012
@@ -194,13 +194,37 @@ def allowed_values
def expected_message
if @options.key?(:expected_message)
if Symbol === @options[:expected_message]
- default_error_message(@options[:expected_message], :model_name => model_name, :attribute => @attribute)
+ default_expected_message
else
@options[:expected_message]
end
end
end
+ def default_expected_message
+ if strict?
+ default_full_message
+ else
+ default_attribute_message
+ end
+ end
+
+ def default_full_message
+ "#{human_attribute_name} #{default_attribute_message}"
+ end
+
+ def human_attribute_name
+ @instance.class.human_attribute_name(@attribute)
+ end
+
+ def default_attribute_message
+ default_error_message(
+ @options[:expected_message],
+ :model_name => model_name,
+ :attribute => @attribute
+ )
+ end
+
def model_name
@instance.class.to_s.underscore
end
@@ -6,6 +6,12 @@ class ValidationMatcher # :nodoc:
def initialize(attribute)
@attribute = attribute
+ @strict = false
+ end
+
+ def strict
+ @strict = true
+ self
end
def negative_failure_message
@@ -24,6 +30,9 @@ def allows_value_of(value, message = nil)
new(value).
for(@attribute).
with_message(message)
+ if strict?
+ allow = allow.strict
+ end
if allow.matches?(@subject)
@negative_failure_message = allow.failure_message
true
@@ -38,6 +47,9 @@ def disallows_value_of(value, message = nil)
new(value).
for(@attribute).
with_message(message)
+ if strict?
+ disallow = disallow.strict
+ end
if disallow.matches?(@subject)
@failure_message = disallow.negative_failure_message
false
@@ -46,6 +58,10 @@ def disallows_value_of(value, message = nil)
true
end
end
+
+ def strict?
+ @strict
+ end
end
end
end
@@ -120,4 +120,22 @@ def custom_validation
@model.should_not ensure_inclusion_of(:attr).in_array(['one', 'two']).allow_nil(false)
end
end
+
+ if Rails::VERSION::STRING.to_f >= 3.2
+ context "a strict attribute which must be included in a range" do
+ before do
+ @model = define_model(:example, :attr => :integer) do
+ validates_inclusion_of :attr, :in => 2..5, :strict => true
+ end.new
+ end
+
+ it "should accept ensuring the correct range" do
+ @model.should ensure_inclusion_of(:attr).in_range(2..5).strict
+ end
+
+ it "should not accept ensuring another range" do
+ @model.should_not ensure_inclusion_of(:attr).in_range(2..6).strict
+ end
+ end
+ end
end
@@ -117,4 +117,19 @@
end
end
+ if Rails::VERSION::STRING.to_f >= 3.2
+ context "a strictly required attribute" do
+ before do
+ define_model :example, :attr => :string do
+ validates_presence_of :attr, :strict => true
+ end
+ @model = Example.new
+ end
+
+ it "should require a value" do
+ @model.should validate_presence_of(:attr).strict
+ end
+ end
+ end
+
end

0 comments on commit d9289fa

Please sign in to comment.