From 7c649b2c85ecc05ee74a1b869a2b5d3a626d59be Mon Sep 17 00:00:00 2001 From: Ben Taitelbaum Date: Fri, 3 Sep 2010 12:07:37 -0400 Subject: [PATCH] Add the attributes for the parent factory before those for the child, so that the child can reference parent attributes; fixes gh-15 --- lib/factory_girl/factory.rb | 5 ++++- spec/factory_girl/factory_spec.rb | 13 +++++++++++++ 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/lib/factory_girl/factory.rb b/lib/factory_girl/factory.rb index 10458077f..0d68ba672 100644 --- a/lib/factory_girl/factory.rb +++ b/lib/factory_girl/factory.rb @@ -55,11 +55,14 @@ def initialize (name, options = {}) #:nodoc: def inherit_from(parent) #:nodoc: @options[:class] ||= parent.class_name @options[:default_strategy] ||= parent.default_strategy + + new_attributes = [] parent.attributes.each do |attribute| unless attribute_defined?(attribute.name) - @attributes << attribute.clone + new_attributes << attribute.clone end end + @attributes.unshift *new_attributes end def define_attribute(attribute) diff --git a/spec/factory_girl/factory_spec.rb b/spec/factory_girl/factory_spec.rb index 08a22dac7..e66d492b2 100644 --- a/spec/factory_girl/factory_spec.rb +++ b/spec/factory_girl/factory_spec.rb @@ -196,6 +196,19 @@ child.attributes.size.should == 1 child.attributes.first.should == @child_attr end + + it "should allow to use parent attributes in defining additional attributes" do + User.class_eval { attr_accessor :name, :email } + + child = FactoryGirl::Factory.new(:child) + @child_attr = FactoryGirl::Attribute::Dynamic.new(:email, lambda {|u| "#{u.name}@example.com"}) + child.define_attribute(@child_attr) + child.inherit_from(@factory) + child.attributes.size.should == 2 + + result = child.run(FactoryGirl::Proxy::Build, {}) + result.email.should == 'value@example.com' + end end it "inherit all callbacks" do