Permalink
Browse files

Tests and fix for validates_presence of :allow_nil, :allow_blank

Conflicts:
	activemodel/lib/active_model/errors.rb
  • Loading branch information...
1 parent d9ce4fa commit d4c30a0226386f291bd8b1959fed12b3aca19164 @ColinDKelley ColinDKelley committed with rafaelfranca Dec 26, 2012
@@ -322,9 +322,15 @@ def add_on_empty(attributes, options = {})
# person.errors.messages
# # => {:name=>["can't be blank"]}
def add_on_blank(attributes, options = {})
+ return if options[:allow_blank]
+
Array(attributes).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
@@ -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 d4c30a0

Please sign in to comment.