在factory_girl定义中指定随机关联对象

发布于 2024-09-13 10:48:37 字数 679 浏览 4 评论 0原文

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

柳絮泡泡 2024-09-20 10:48:37

您希望使用 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)) }

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文