好吧,伙计们。这怎么有意义呢?两个嵌套工厂(被FactoryGirl视为继承)不应相互冲突。到底他妈发生了什么?它不是继承,也不是。我不知道为什么他们称之为继承,如果不是。我只是做错了吗? (注意f.account_type
)
看看下面的工厂定义。
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
当我运行测试时,我收到此错误。
Failure/Error: partner = FactoryGirl.create(:business_partner)
FactoryGirl::AttributeDefinitionError:
Attribute already defined: account_type
只是为了完整性,我的规格。
# 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's fullname as a string"
end
答案 0 :(得分:10)
在business_partner
和personal_partner
工厂定义中,您指的是f
,这是partner
工厂的定义。这意味着,即使account_type
定义出现在子工厂中,两者都在父工厂中定义。
在较新版本的FactoryGirl中解决此问题的最简单方法是完全删除阻止参数。
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
如果您喜欢块参数,只需确保接受每个工厂定义的参数并使用不同的变量名称。