Skip to content
Browse files

Tests and fix for validates_presence of :allow_nil, :allow_blank

  • Loading branch information...
1 parent 885f59f commit 1970633aa4a846003474cc06868d1226b9f38b94 @ColinDKelley committed Dec 26, 2012
View
7 activemodel/lib/active_model/errors.rb
@@ -250,9 +250,14 @@ def add_on_empty(attributes, options = {})
# Will add an error message to each of the attributes in +attributes+ that is blank (using Object#blank?).
def add_on_blank(attributes, options = {})
+ return if options[:allow_blank]
[attributes].flatten.each do |attribute|
value = @base.send(:read_attribute_for_validation, attribute)
- add(attribute, :blank, options) if value.blank?
+ if value.nil?
+ add(attribute, :blank, options) unless options[:allow_nil]
+ elsif value.blank?
+ add(attribute, :blank, options)
+ end
end
end
View
34 activemodel/test/cases/validations/presence_validation_test.rb
@@ -70,4 +70,38 @@ def test_validates_presence_of_for_ruby_class_with_custom_reader
p[:karma] = "Cold"
assert p.valid?
end
+
+ def test_allow_nil
+ Topic.validates_presence_of(:title, :allow_nil => true)
+
+ t = Topic.new(:title => "something")
+ assert t.valid?, t.errors.full_messages
+
+ t.title = ""
+ assert t.invalid?
+ assert_equal ["can't be blank"], t.errors[:title]
+
+ t.title = " "
+ assert t.invalid?, t.errors.full_messages
+ assert_equal ["can't be blank"], t.errors[:title]
+
+ t.title = nil
+ assert t.valid?, t.errors.full_messages
+ end
+
+ def test_allow_blank
+ Topic.validates_presence_of(:title, :allow_blank => true)
+
+ t = Topic.new(:title => "something")
+ assert t.valid?, t.errors.full_messages
+
+ t.title = ""
+ assert t.valid?, t.errors.full_messages
+
+ t.title = " "
+ assert t.valid?, t.errors.full_messages
+
+ t.title = nil
+ assert t.valid?, t.errors.full_messages
+ end
end

0 comments on commit 1970633

Please sign in to comment.
Something went wrong with that request. Please try again.