2013-08-02 99 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