From d4c30a0226386f291bd8b1959fed12b3aca19164 Mon Sep 17 00:00:00 2001
From: Colin Kelley <colindkelley@gmail.com>
Date: Wed, 26 Dec 2012 10:31:05 -0800
Subject: Tests and fix for validates_presence of :allow_nil, :allow_blank

Conflicts:
	activemodel/lib/active_model/errors.rb
---
 activemodel/lib/active_model/errors.rb             |  8 ++++-
 .../cases/validations/presence_validation_test.rb  | 34 ++++++++++++++++++++++
 2 files changed, 41 insertions(+), 1 deletion(-)

(limited to 'activemodel')

diff --git a/activemodel/lib/active_model/errors.rb b/activemodel/lib/active_model/errors.rb
index 963e52bff3..92c2512aa4 100644
--- a/activemodel/lib/active_model/errors.rb
+++ b/activemodel/lib/active_model/errors.rb
@@ -322,9 +322,15 @@ module ActiveModel
     #   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
 
diff --git a/activemodel/test/cases/validations/presence_validation_test.rb b/activemodel/test/cases/validations/presence_validation_test.rb
index 510c13a7c3..fe2ee7b409 100644
--- a/activemodel/test/cases/validations/presence_validation_test.rb
+++ b/activemodel/test/cases/validations/presence_validation_test.rb
@@ -70,4 +70,38 @@ class PresenceValidationTest < ActiveModel::TestCase
     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
-- 
cgit v1.2.3