如何使用 Factory Girl 定义多个关联对象?
Factory Girl 文档提供了这种语法来创建(我猜)父子关联......
Factory.define :post do |p|
p.author {|a| a.association(:user) }
end
帖子属于用户(其“作者”)。
如果您想定义一个工厂来创建具有一堆 Post
的 User
,该怎么办?
或者如果是多对多的情况怎么办(例如,请参阅下面的更新)?
更新
我以为我已经弄清楚了。 我尝试了这个...
Factory.define(:user) do |f|
f.username { Factory.next(:username) }
# ...
f.roles { |user|
[
Factory(:role),
Factory(:role, {:name => 'EDIT_STAFF_DATA'})
]
}
end
一开始似乎有效,但后来我收到验证错误,因为 FG 试图使用相同的用户名和电子邮件保存用户两次。
所以我回到原来的问题。 如果你有一个多对多的关系,比如Users
和Roles
,你如何定义一个工厂来返回Users
和一些相关的角色
? 请注意,Roles
必须是唯一的,因此我不能让 FG 每次创建 User
时都在数据库中创建新的“ADMIN”Role
>。
The Factory Girl docs offer this syntax for creating (I guess) parent-child associations...
Factory.define :post do |p|
p.author {|a| a.association(:user) }
end
A post belongs to a User (its "author").
What if you want to define a Factory to create User
s, that have a bunch of Post
s?
Or what if it's a many-to-many situation (see update below for example)?
UPDATE
I thought I had figured it out. I tried this...
Factory.define(:user) do |f|
f.username { Factory.next(:username) }
# ...
f.roles { |user|
[
Factory(:role),
Factory(:role, {:name => 'EDIT_STAFF_DATA'})
]
}
end
It seemed to work at first, but then I got validation errors because F.G. was trying to save the user twice with same username and email.
So I return to my original question. If you have a many-to-many relationship, like say Users
and Roles
, how can you define a Factory that will return Users
with some associated Roles
? Note that Roles
must be unique, so I can't have F.G. creating a new "ADMIN" Role
in the DB every time it creates a User
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我不确定这是否是最正确的方法,但它确实有效。
I'm not sure if this is the most correct way of doing it, but it works.
最近的对工厂女孩的更新允许关联用回调块指定
A recent update to factory girl allows associations to be specified with callback blocks
我创建了一个 active_factory 插件,它可以处理您在规范中的情况,如下所示:
如果有兴趣,我可以尝试与factory_girl工厂创建集成。
I created an active_factory plugin, that deals with your situation in spec like this:
If there is an interest, i may try to create integration with factory_girl factories.