我与具有验证关联的对象具有标准的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
答案 0 :(得分: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
我所做的只是将创建的地址实例直接添加到其员工地址。在这个后构建循环中,您当然也可以使用相同的员工创建其他地址并将其添加到列表中。