Ruby-on-rails FactoryBot:多次创建同一个对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18445828/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
FactoryBot:create the same object multiple times
提问by usha
In one of my rspec test, I am creating multiple objects from the same factory definition
在我的 rspec 测试之一中,我从同一个工厂定义中创建了多个对象
Eg
例如
FactoryBot.create(:model_1)
FactoryBot.create(:model_1)
FactoryBot.create(:model_1)
Is there a method that factory_botprovides to do this in one line
是否有一种方法factory_bot可以在一行中执行此操作
I know that I can do
我知道我能做到
3.times {FactoryBot.create(:model_1)}
But I am looking for something that factory_botprovides for creating multiple objects of the same model.
但我正在寻找factory_bot可以创建同一模型的多个对象的东西。
回答by apneadiving
You can create a list like this (hence create x objects at once):
您可以创建这样的列表(因此一次创建 x 个对象):
FactoryBot.create_list(:model_1, 3)
Documentation lives here.
文档保存在这里。
回答by Nishutosh Sharma
FactoryBot.create_list :factory_name, 2, attribute_name: 'value'
Simple and best way to move.
简单和最好的移动方式。
You can ignore the attribute names if not needed the same, and use sequence instead.
如果不需要相同的属性名称,您可以忽略它们,而使用序列代替。
回答by Cody Elhard
If you need to do this for a model with validation, I was able to do the following in my test.
如果您需要对带有验证的模型执行此操作,我可以在测试中执行以下操作。
10.times do |i|
create(
:object,
property: i
)
end
回答by cromac
Not sure if this has been updated since the answer was posted, but now you would do the following
不确定自答案发布后这是否已更新,但现在您将执行以下操作
FactoryBot.create_list(:model_1, 3)
see Getting Started
请参阅 入门

