![](/img/trans.png)
[英]What's the best practice for setting up associations with factory_girl in cucumber?
[英]factory_girl's Cucumber steps and optional associations
我有以下型号:
class Person < ActiveRecord::Base
belongs_to :family
end
class Family < ActiveRecord::Base
end
和以下工厂:
Factory.define :person do |p|
p.association :family
end
Factory.define :family do |f|
end
我正在使用factory_girl的Cucumber步骤,如下所示:
Given the following people exist:
| First name | Last name |
| John | Doe |
Given the following people exist:
| First name | Last name | Family |
| John | Doe | Name: Doe's family |
我想使用第一种形式创建没有关联家庭的人,而后一种形式创建具有家庭的人。 现在每个人都有一个家庭。 实际上,使用第一种形式会失败,因为在Family
类中也有validates_presence_of :name
。
如果我从Person
工厂定义中删除p.association :family
,则后一种形式将失败,因为它试图将字符串设置为关联记录(它运行类似于family = "Name: ..."
)。
在factory_girl定义的黄瓜步骤中是否可以有可选的关联?
我将创建另一个工厂,例如:
Factory.define :orphan, :class => "Person" do |factory|
# does not belong to a family
end
然后在您的第一个设置中使用它:
Given the following orphans exist:
| First name | Last name |
| John | Doe |
我将使您的默认用户成为无关联的人,然后定义一个添加该关联的子工厂,这可能有点违反直觉,但这是建立类层次结构的正确方法:
Factory.define(:person) do |f|
end
Factory.define(:family_member, :parent => :person) do |f|
f.association(:family)
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.