2013-08-02 138 views
0

我有一個標準的has_many關係與一個驗證關聯的對象。但是我不知道如何避免錯誤堆棧太深。FactoryGirl + Rspec關聯驗證has_many

這裏我的兩個型號

class Address < ActiveRecord::Base 
belongs_to :employee, :inverse_of => :addresses 
end 

class Employee < ActiveRecord::Base 

    has_many :addresses, :dependent => :destroy, :inverse_of => :employee  #inverse of  can use addresses.employee 
    has_many :typings 
    has_many :types, through: :typings 

    validates :addresses, length: { minimum: 1 } 
    validates :types, length: { minimum: 1 } 


end 

這裏我的工廠

FactoryGirl.define do 
factory :address, class: Address do 
    address_line 'test' 
    name 'Principal' 
    city 'test' 
    zip_code 'test' 
    country 'france' 
end 
end 

FactoryGirl.define do 
factory :employee_with_address_type, class: Employee do |e| 
    e.firstname 'Jeremy' 
    e.lastname 'Pinhel' 
    e.nationality 'France' 
    e.promo  '2013' 
    e.num_mobile 'Test' 
    e.types { |t| [t.association(:type)] } 
    after :build do |em| 
    em.addresses << FactoryGirl.build(:address) 
    end 
end 
end 

這裏我的模型試驗

describe Address do 
    context 'valid address' do 
    let(:address) {FactoryGirl.build(:address)} 
    subject {address} 

    #before(:all) do 
    # @employee = FactoryGirl.build(:employee_with_address_type) 
    #end 

    it 'presence of all attributes' do 
    should be_valid 
    end 
end 
end 

有人能幫助我瞭解如何解決這個問題?我嘗試與我的工廠不同的組合,但沒有成功。

編輯:

class Employee < ActiveRecord::Base 

    has_many :addresses, :dependent => :destroy, :inverse_of => :employee  #inverse of  can use addresses.employee 
    has_many :typings 
    has_many :types, through: :typings 

    validates_associated :addresses 
    validates_associated :types 


end 
+1

你可以發佈例外嗎? – unnu

+0

這裏我的異常失敗/錯誤:應be_valid得到的錯誤:員工不能爲空,如果添加關聯:我的地址工廠的員工已經得到堆棧級別太深 – Pinou

回答

0

你可以重寫你的工廠如下:

 FactoryGirl.define do 
     factory :address_with_employee, class: Address do 
     address_line 'test' 
     name 'Principal' 
     city 'test' 
     zip_code 'test' 
     country 'france' 
     association :employee, :factory => :employee_with_address_type 
     after :build do |ad| 
      ad.employee.addresses << ad 
     end 
     end 
    end 

    FactoryGirl.define do 
     factory :employee_with_address_type, class: Employee do |e| 
     e.firstname 'Jeremy' 
     e.lastname 'Pinhel' 
     e.nationality 'France' 
     e.promo  '2013' 
     e.num_mobile 'Test' 
     e.types { |t| [t.association(:type)] } 
     end 
    end 

我所做的只是直接添加創建的地址實例員工地址。在這個構建循環之後,你當然也可以用同一個員工創建額外的地址並將它們添加到列表中。

+0

謝謝,我明白這個解決方案,但我仍然有一個失敗 - >地址不能爲空,因爲我在我的Employee模型中驗證了地址。我如何解決這個問題? – Pinou

+0

我將我的約束更改爲:valides_associated的地址,現在測試很好。 – Pinou