好的伙计们。这怎么说得通?两个嵌套的工厂(被 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
最佳答案
在 business_partner
和 personal_partner
工厂定义中,您指的是 f
,它是 partner< 的定义
工厂。这意味着,即使 account_type
定义出现在子工厂中,它们都是在父工厂中定义的。
在较新版本的 FactoryGirl 中解决此问题的最简单方法是完全删除 block 参数。
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
如果您喜欢 block 参数,只需确保为每个工厂定义接受一个参数并使用不同的变量名即可。
关于ruby - FactoryGirl 继承属性已经定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21534667/