has_many尊重factory_girl中的构建策略 [英] has_many while respecting build strategy in factory_girl

查看:50
本文介绍了has_many尊重factory_girl中的构建策略的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

# Models
class User < ActiveRecord::Base
  has_many :items 
end 

class Items < ActiveRecord::Base
  belongs_to :user 
  validates_presence_of :user_id 
end 

# Factories
Factory.define(:user) do |u| 
  u.name "foo" 
end 

Factory.define(:user_with_items, :parent => :user) do |u| 
  u.items {|items| [items.association(:item), items.association(:item)]} 
end

Factory.define(:item) do |i| 
  i.color "red" 
end 

Factory.define(:item_with_user, :parent => :user) do |i| 
  i.association(:user) 
end

问题

如果运行@user = Factory(:user_with_items),则@user.items包含两个项目.问题是这些项目与数据库中的用户没有关联.如果重新加载关联@user.items(true),则将返回一个空数组.我知道你可以建造它们 手动或自己创建帮助器方法来构建对象图,但是我想避免这种情况.

Problem

If you run @user = Factory(:user_with_items) then @user.items contains the two items. The issue is that the items aren't associated with the user in the database. If you reload the association @user.items(true) then you get back an empty array. I know you can build them manually or create helper methods on your own to build the object graph, but I'd like to avoid that.

所以,我的问题是,在尊重构建策略的同时,如何在factory_girl中建立has_many关系?

So, my question is how can you build up a has_many relationship in factory_girl while respecting the build strategy?

推荐答案

我用继承和所有这些正确地编写了它.我的提交内容已合并到此处

I wrote it properly with inheritance and all that. My commits are merged in here and here.

现在在FactoryGirl 1.2.3中,哇!

It's now in FactoryGirl 1.2.3, woot!

这篇关于has_many尊重factory_girl中的构建策略的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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