2013-09-26 40 views
2

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

這些確實是模型的完整定義嗎?你分享的錯誤信息會提示他們有更多的信息,比如驗證。另外,鑑於直接和間接關聯導致創建兩個組織,您的':coverage_1'工廠在組織獨特性方面的意圖是什麼? –

回答

3

錯誤消息意味着: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 
+0

你理解我錯了。您的解決方案始終使用新的:organization_code創建組織。例如,我想爲一個組織創建2個訂閱者。第一個訂閱者創建得很好,但接下來沒有,因爲之前創建了帶有這些參數的組織。 – Nike0

+0

要爲一個組織創建2個訂閱者,請嘗試以下代碼: org = create(:organization_benefit) subscriber1 = create(:subscriber_875450002,organization:org) subscriber2 = create(:subscriber_875450002,organization:org) –