通过 factory_girl 协会查找或创建记录 [英] Find or create record through factory_girl association

查看:16
本文介绍了通过 factory_girl 协会查找或创建记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个属于组的用户模型.组必须具有唯一的名称属性.用户工厂和组工厂定义为:

I have a User model that belongs to a Group. Group must have unique name attribute. User factory and group factory are defined as:

Factory.define :user do |f|
  f.association :group, :factory => :group
  # ...
end

Factory.define :group do |f|
  f.name "default"
end

当创建第一个用户时,也会创建一个新组.当我尝试创建第二个用户时,它失败了,因为它想再次创建相同的组.

When the first user is created a new group is created too. When I try to create a second user it fails because it wants to create same group again.

有没有办法告诉 factory_girl 关联方法首先查找现有记录?

Is there a way to tell factory_girl association method to look first for an existing record?

注意:我确实尝试定义一个方法来处理这个问题,但是我不能使用 f.association.我希望能够在这样的 Cucumber 场景中使用它:

Note: I did try to define a method to handle this, but then I cannot use f.association. I would like to be able to use it in Cucumber scenarios like this:

Given the following user exists:
  | Email          | Group         |
  | test@email.com | Name: mygroup |

这只有在工厂定义中使用关联时才有效.

and this can only work if association is used in Factory definition.

推荐答案

我最终使用了在网上找到的各种方法,其中一个是根据 dadyfuzz 在另一个答案中所建议的继​​承工厂.

I ended up using a mix of methods found around the net, one of them being inherited factories as suggested by duckyfuzz in another answer.

我做了以下:

# in groups.rb factory

def get_group_named(name)
  # get existing group or create new one
  Group.where(:name => name).first || Factory(:group, :name => name)
end

Factory.define :group do |f|
  f.name "default"
end

# in users.rb factory

Factory.define :user_in_whatever do |f|
  f.group { |user| get_group_named("whatever") }
end

这篇关于通过 factory_girl 协会查找或创建记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆