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

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

问题描述

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

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

Factory.define:group do | f |
f.namedefault
end

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



有一种方法告诉factory_girl关联方法先查找现有记录?



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

 给定以下用户存在:
|电子邮件|组|
| test@email.com |名称:mygroup |

这只能在工厂定义中使用关联时才能使用。



$ b

我做了以下操作:

 #in groups.rb factory 

def get_group_named(name)
#获取现有组或创建新组
Group.where(:name => name).first ||工厂(:group,:name => name)
end

Factory.define:group do | f |
f.namedefault
end

#in users.rb factory

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


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.

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

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.

解决方案

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.

I did following:

# 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天全站免登陆