From bb767af51b4e3afc7755af1c7cb60a6018c55fe5 Mon Sep 17 00:00:00 2001 From: Jeffrey Hardy Date: Fri, 6 Mar 2009 17:43:00 -0500 Subject: [PATCH] Add ActiveRecord::Base#invalid? as the opposite of #valid? --- activerecord/lib/active_record/validations.rb | 5 +++++ activerecord/test/cases/validations_test.rb | 13 ++++++++++++- 2 files changed, 17 insertions(+), 1 deletions(-) diff --git a/activerecord/lib/active_record/validations.rb b/activerecord/lib/active_record/validations.rb index 8f3c805..89dffa5 100644 --- a/activerecord/lib/active_record/validations.rb +++ b/activerecord/lib/active_record/validations.rb @@ -1040,6 +1040,11 @@ module ActiveRecord errors.empty? end + # Performs the opposite of valid?. Returns true if errors were added, false otherwise. + def invalid? + !valid? + end + # Returns the Errors object that holds all information about attribute error messages. def errors @errors ||= Errors.new(self) diff --git a/activerecord/test/cases/validations_test.rb b/activerecord/test/cases/validations_test.rb index cbb1841..1eab653 100644 --- a/activerecord/test/cases/validations_test.rb +++ b/activerecord/test/cases/validations_test.rb @@ -169,7 +169,7 @@ class ValidationsTest < ActiveRecord::TestCase assert_equal person.first_name, "Mary", "should be ok when no attributes are passed to create!" end end - end + end def test_single_error_per_attr_iteration r = Reply.new @@ -1421,6 +1421,17 @@ class ValidationsTest < ActiveRecord::TestCase assert_equal "can't be blank", t.errors.on("title").first end + def test_invalid_should_be_the_opposite_of_valid + Topic.validates_presence_of :title + + t = Topic.new + assert t.invalid? + assert t.errors.invalid?(:title) + + t.title = 'Things are going to change' + assert !t.invalid? + end + # previous implementation of validates_presence_of eval'd the # string with the wrong binding, this regression test is to # ensure that it works correctly -- 1.6.1