From 52d49fdee82cdc592f7527b42c8862a2a1b330c9 Mon Sep 17 00:00:00 2001 From: Wolfram Arnold Date: Mon, 29 Jun 2009 14:20:15 -0700 Subject: [PATCH] Add test to verify that the new :inverse_of association option will indeed fix the validation problem for a belongs_to relationship that validates_presence_of the parent, when both the parent and the child are new (in-memory) records. Also check that this works when the parents adds child via nested_attributes_for. Lastly, add a require 'models/pet' so that test can be run independently (was failing due to that missing dependency). --- .../validations/association_validation_test.rb | 36 ++++++++++++++++++++ 1 files changed, 36 insertions(+), 0 deletions(-) diff --git a/activerecord/test/cases/validations/association_validation_test.rb b/activerecord/test/cases/validations/association_validation_test.rb index b1203c1..fb5c928 100644 --- a/activerecord/test/cases/validations/association_validation_test.rb +++ b/activerecord/test/cases/validations/association_validation_test.rb @@ -3,6 +3,9 @@ require "cases/helper" require 'models/topic' require 'models/reply' require 'models/owner' +require 'models/pet' +require 'models/man' +require 'models/interest' class AssociationValidationTest < ActiveRecord::TestCase fixtures :topics, :owners @@ -98,4 +101,37 @@ class AssociationValidationTest < ActiveRecord::TestCase end end end + + def test_validates_presence_of_belongs_to_association__parent_is_new_record + repair_validations(Interest) do + # Note that Interest and Man have the :inverse_of option set + Interest.validates_presence_of(:man) + man = Man.new(:name => 'John') + interest = man.interests.build(:topic => 'Airplanes') + assert interest.valid?, "Expected interest to be valid, but was not. Interest should have a man object associated" + end + end + + def test_validates_presence_of_belongs_to_association__existing_parent + repair_validations(Interest) do + Interest.validates_presence_of(:man) + man = Man.create!(:name => 'John') + interest = man.interests.build(:topic => 'Airplanes') + assert interest.valid?, "Expected interest to be valid, but was not. Interest should have a man object associated" + end + end + + def test_validates_presence_of_for_belongs_to_works_with_nested_attributes + Man.accepts_nested_attributes_for(:interests) + repair_validations(Interest) do + Interest.validates_presence_of(:man) + assert_difference 'Man.count' do + assert_difference 'Interest.count', 2 do + man = Man.create!(:name => 'John', + :interests_attributes => [{:topic=>'Cars'}, {:topic=>'Sports'}]) + assert_equal 2, man.interests.count + end + end + end + end end -- 1.5.6.3