From f5d4db10855978ee054687ba2e04882f65e76630 Mon Sep 17 00:00:00 2001 From: Joshua Clayton Date: Fri, 16 Mar 2012 13:04:31 -0400 Subject: [PATCH] Ensure attributes set on instance are calculated uniquely This fixes a bug where assignment occurs multiple times; in the case of nested attributes, assignment mutates the instance, meaning that it occurring multiple times will cause issues. Closes #314 --- lib/factory_girl/attribute_assigner.rb | 2 +- spec/acceptance/nested_attributes_spec.rb | 32 +++++++++++++++++++++++ 2 files changed, 33 insertions(+), 1 deletion(-) create mode 100644 spec/acceptance/nested_attributes_spec.rb diff --git a/lib/factory_girl/attribute_assigner.rb b/lib/factory_girl/attribute_assigner.rb index 5bdf873..4eae168 100644 --- a/lib/factory_girl/attribute_assigner.rb +++ b/lib/factory_girl/attribute_assigner.rb @@ -37,7 +37,7 @@ module FactoryGirl end def attributes_to_set_on_instance - attribute_names_to_assign - @attribute_names_assigned + (attribute_names_to_assign - @attribute_names_assigned).uniq end def attributes_to_set_on_hash diff --git a/spec/acceptance/nested_attributes_spec.rb b/spec/acceptance/nested_attributes_spec.rb new file mode 100644 index 0000000..f1cd350 --- /dev/null +++ b/spec/acceptance/nested_attributes_spec.rb @@ -0,0 +1,32 @@ +require "spec_helper" + +describe "association assignment from nested attributes" do + before do + define_model("Post", :title => :string) do + has_many :comments + accepts_nested_attributes_for :comments + end + + define_model("Comment", :post_id => :integer, :body => :text) do + belongs_to :post + end + + FactoryGirl.define do + factory :post do + comments_attributes { [FactoryGirl.attributes_for(:comment), FactoryGirl.attributes_for(:comment)] } + end + + factory :comment do + sequence(:body) {|n| "Body #{n}" } + end + end + end + + it "assigns the correct amount of comments" do + FactoryGirl.create(:post).comments.count.should == 2 + end + + it "assigns the correct amount of comments when overridden" do + FactoryGirl.create(:post, :comments_attributes => [FactoryGirl.attributes_for(:comment)]).comments.count.should == 1 + end +end