在factory_girl定义中指定随机关联对象
factory_girl
中有没有办法指定关联应指向的随机实例?例如,我有一个 Like
对象,它 belongs_to
一个 User
和一个 SocialUnit
。我希望 Like
工厂随机选择一个现有的 User
和一个随机的 SocialUnit
来点赞,而不是仅仅生成一个新的。下面的代码片段是有效的:
Factory.define :like do |f|
if User.all.count > 0
f.user User.all.sort_by{ rand }.first
else
f.association :user
end
end
它确实选择了一个随机用户,但似乎随机用户只被选择一次,因为运行这个
def create_hauls
5.times do |i|
Factory(:haul)
end
end
会创建一堆对同一用户的喜欢。我想这是有道理的......工厂被定义一次,然后重复使用很多次。
我可以使用序列来强制随机性;有没有办法在工厂定义中定义它,或者顺序是最好的方法吗?
谢谢。
Is there a way in factory_girl
to specify a random instance that an association should point to? For example, I have a Like
object which belongs_to
one User
and one SocialUnit
. I want the factory for Like
to pick a random existing User
and a random SocialUnit
to like, instead of just generating a new one. The below snippet sort of works:
Factory.define :like do |f|
if User.all.count > 0
f.user User.all.sort_by{ rand }.first
else
f.association :user
end
end
It indeed picks a random user, but it seems like the random user only gets picked once, because running this
def create_hauls
5.times do |i|
Factory(:haul)
end
end
creates a bunch of likes all with the same user. I guess that makes sense... the factory gets defined once, and then reused a bunch of times.
I could use a sequence to force randomness; is there a way to define it within the factory definition, or is the sequence the best way to do it?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您希望使用 lazy 属性,而不是在定义工厂时定义用户。这将在每次使用工厂时定义用户。
f.user { (User.all.count > 0 ? User.all.sort_by{ rand }.first : Factory.create(:user)) }
You want to use a lazy attribute instead of defining the user when the factory is defined. This will define the user each time the factory is used instead.
f.user { (User.all.count > 0 ? User.all.sort_by{ rand }.first : Factory.create(:user)) }