我有一个Person
与具有多对多关系的模型Email
模型,我想创建一个工厂,让我为该人生成名字和姓氏(这已经完成)并创建一个基于该人姓名的电子邮件地址。这是我要创建的person
's name:
Factory.sequence :first_name do |n|
first_name = %w[FirstName1 FirstName2] # ... etc (I'm using a real subset of first names)
first_name[(rand * first_name.length)]
end
Factory.sequence :last_name do |n|
last_name = %w[LastName1 LastName2] # ... etc (I'm using a real subset of last names)
last_name[(rand * last_name.length)]
end
Factory.define :person do |p|
#p.id ???
p.first_name { Factory.next(:first_name) }
p.last_name { Factory.next(:last_name) }
#ok here is where I'm stuck
#p.email_addresses {|p| Factory(:email_address_person_link) }
end
Factory.define :email_address_person_link do |eapl|
# how can I link this with :person and :email_address ?
# eapl.person_id ???
# eapl.email_address_id ???
end
Factory.define :email_address do |e|
#how can I pass p.first_name and p.last_name into here?
#e.id ???
e.email first_name + "." + last_name + "@test.com"
end
好吧,我想我现在明白你在问什么了。像这样的东西应该有效(未经测试,但我在另一个项目中做了类似的事情):
Factory.define :person do |f|
f.first_name 'John'
f.last_name 'Doe'
end
Factory.define :email do |f|
end
# This is optional for isolating association testing; if you want this
# everywhere, add the +after_build+ block to the :person factory definition
Factory.define :person_with_email, :parent => :person do |f|
f.after_build do |p|
p.emails << Factory(:email, :email => "#{p.first_name}.#{p.last_name}@gmail.com")
# OR
# Factory(:email, :person => p, :email => "#{p.first_name}.#{p.last_name}@gmail.com")
end
end
如前所述,使用第三个独立工厂是可选的。就我而言,我并不总是想为每个测试生成关联,因此我创建了一个单独的工厂,仅在一些特定测试中使用。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)