FactoryGirl Inheritance Attribute Already Defined

Ok guys. How does that make sense? Two nested factories (which are considered FactoryGirl inheritance) should not conflict with each other. What the hell is going on? Either this is not inheritance, or it is. I donโ€™t know why they would call this inheritance if it werenโ€™t. Am I just doing something wrong? (Notification f.account_type )

Have a look at the factory definition below.

 factory :partner do |f| f.company_name { Faker::Company.name } f.username { Faker::Internet.user_name } f.password { Faker::Internet.password } f.password_confirmation { password } f.pid { Faker::Lorem.word } f.association :primary_contact # Inherited factory :business_partner do f.account_type "business" f.tax_id { Faker::Company.duns_number } end # Inherited factory :personal_partner do f.account_type "personal" f.ssn { Faker::Company.duns_number } end end 

When I run my tests, I get this error.

 Failure/Error: partner = FactoryGirl.create(:business_partner) FactoryGirl::AttributeDefinitionError: Attribute already defined: account_type 

And just for the sake of completeness of my specification.

 # spec/models/partner.rb require 'spec_helper' require 'pp' describe Partner do it "has a valid factory" do partner = FactoryGirl.create(:business_partner) partner.should be_valid puts partner end it "is invalid without a firstname" do # FactoryGirl.build(:partner_contact, first_name: nil).should_not be_valid end it "is invalid without a lastname" do # FactoryGirl.build(:partner_contact, last_name: nil).should_not be_valid end it "is invalid without an email address" do # FactoryGirl.build(:partner_contact, email: nil).should_not be_valid end #it "returns a contact fullname as a string" end 
+7
ruby ruby-on-rails-4 rspec factory-bot
source share
1 answer

In the definitions of business_partner and personal_partner factory, you refer to f , which is the definition for partner factory. This means that although account_type definitions are found inside child factories, both are defined at the parent factory.

The easiest way to fix this in newer versions of FactoryGirl is to completely remove the block parameter.

 factory :partner do company_name { Faker::Company.name } username { Faker::Internet.user_name } password { Faker::Internet.password } password_confirmation { password } pid { Faker::Lorem.word } association :primary_contact # Inherited factory :business_partner do account_type "business" tax_id { Faker::Company.duns_number } end # Inherited factory :personal_partner do account_type "personal" ssn { Faker::Company.duns_number } end end 

If you like block parameters, just make sure you take a parameter for each factory definition and use a different variable name.

+10
source share

All Articles