gpt4 book ai didi

ruby-on-rails-3 - Ruby 工厂女孩创建多个对象

转载 作者:行者123 更新时间:2023-11-28 20:24:49 25 4
gpt4 key购买 nike

我是使用 Factory Girl 的新手,我觉得我可能对它应该如何工作以及我应该如何使用它有一些误解。这是问题代码的片段。

FactoryGirl.define do                      
factory :li_store , :class => Store do
...store stuff...blah...blah
end

factory :li_line_item_stores_two,:class=>LineItemsStore do
association :store, :factory=>:li_store
association :line_item , :factory=>:li_line_item_two
end
factory :li_line_item_stores_three,:class=>LineItemsStore do
association :store :factory => :li_store
association :line_item , :factory => :li_line_item_three
end

现在,如果我访问 :li_line_item_stores_two 和 :li_line_item_stores_two,每个对象的商店属性都有一个不同的对象。对于我的测试,我需要两个对象都具有相同的存储对象。

有谁知道我缺少 FactoryGirl 的哪个方面,或者我应该如何确保两个对象都引用同一个存储对象?

非常感谢任何帮助。

最佳答案

您想在 factory.rb 文件中定义基线 对象和属性。您不想定义一个对象的一堆不同的相同版本。相反,factories.rb 应该看起来像:

FactoryGirl.define do
factory :li_store do
whatever
end

factory :li_line_item do
whatever
end

factory :li_line_item_store do
association :store, :factory => :li_store
association :line_item, :factory => :li_line_item
end
end

然后在您的测试中可以覆盖这些属性(或者可以保留基线值):

def test_something
store = Factory(:li_store)
li_line_item_store_one = Factory(:li_line_item_store, :store => store)
li_line_item_store_two = Factory(:li_line_item_store, :store => store)
end

有了上面的内容,您现在有两个 li_line_item_store 实例,它们具有不同的订单项和相同的商店。

关于ruby-on-rails-3 - Ruby 工厂女孩创建多个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9085074/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com