我是FactoryGirl的新手。
我有很多FactoryGirl型号。他们彼此相关。
我宣布了以下模型如下:
class Organization < ActiveRecord::Base
has_many :org_plan_years
has_many :subscribers
end
class Subscriber < ActiveRecord::Base
belongs_to :organization
end
class OrgPlanYear < ActiveRecord::Base
belongs_to :organization
has_many :coverages
end
class Coverage < ActiveRecord::Base
belongs_to :subscriber
belongs_to :org_plan_year
belongs_to :organization
end
定义FactoryGirl:
工厂/ organizations.rb
FactoryGirl.define do
factory :organization_benefit, class Organization do
name 'Benefit'
organization_code '2341'
end
end
工厂/ subscribers.rb
FactoryGirl.define do
factory :subscriber_875450002, class: Subscriber do
association :organization, factory: :organization_benefit
ssn 875450002
end
end
工厂/ org_plan_years.rb
FactoryGirl.define do
factory :org_plan_year_benefit, class: OrgPlanYear do
association :organization, factory: :organization_benefit
name 'First OPY'
end
end
工厂/ coverages.rb
FactoryGirl.define do
factory :coverage_1, class: Coverage do
association :subscriber, factory: :subscriber_875450002
association :org_plan_year, factory: :org_plan_year_benefit
end
end
测试样本:
it 'test' do
FactoryGirl.create(:coverage_1)
end
当我运行测试时,我收到如下错误:
ActiveRecord::RecordInvalid: Validation failed: Organization code has already been taken
我认为,问题的原因是我在工厂多次组建组织,但我无法解决问题。
答案 0 :(得分:2)
错误消息表示:organization_benefit工厂应创建具有唯一organization_code值的新Benefit。您可以使用FactoryGirl序列执行此操作。你能试试这段代码吗?
FactoryGirl.define do
factory :organization_benefit, class Organization do
name 'Benefit'
sequence(:organization_code) {|n| 100 + n }
end
end