给定两个对象之间的标准has_many关系.举个简单的例子,我们来看看:
class Order < ActiveRecord::Base
has_many :line_items
end
class LineItem < ActiveRecord::Base
belongs_to :order
end
Run Code Online (Sandbox Code Playgroud)
我想要做的是生成带有存根行项目列表的存根订单.
FactoryGirl.define do
factory :line_item do
name 'An Item'
quantity 1
end
end
FactoryGirl.define do
factory :order do
ignore do
line_items_count 1
end
after(:stub) do |order, evaluator|
order.line_items = build_stubbed_list(:line_item, evaluator.line_items_count, :order => order)
end
end
end
Run Code Online (Sandbox Code Playgroud)
上面的代码不起作用,因为Rails想要在分配line_items时调用order并且FactoryGirl引发异常:
RuntimeError: stubbed models are not allowed to access the database
那么你如何(或者可能)生成一个存根对象,其中has_may集合也是存根的?
# 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
Run Code Online (Sandbox Code Playgroud)
如果你运行@user = Factory(:user_with_items)然后@user.items包含两个项目.问题是项目与数据库中的用户无关.如果你重新加载关联,@user.items(true)那么你会得到一个空数组.我知道你可以手动构建它们或者自己创建辅助方法来构建对象图,但我想避免这种情况.
所以,我的问题是如何在尊重构建策略的同时在factory_girl中建立一个has_many关系?