我是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
我覺得,問題是因爲我在工廠多次建立組織,但是我解決不了問題。
這些確實是模型的完整定義嗎?你分享的錯誤信息會提示他們有更多的信息,比如驗證。另外,鑑於直接和間接關聯導致創建兩個組織,您的':coverage_1'工廠在組織獨特性方面的意圖是什麼? –