1

我是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:

工厂/组织.rb

FactoryGirl.define do
  factory :organization_benefit, class Organization do
    name 'Benefit'
    organization_code '2341'
  end
end

工厂/订阅者.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

我想,这个问题是因为我在工厂里多次成立组织,但我无法解决问题。

4

1 回答 1

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
于 2013-09-26T11:24:42.580 回答