如何在 Factory Girl 中创建/构建工厂的多个实例?
如何创建同一类的多个记录或多个工厂?
我尝试过:
Factory.define :user do |user|
user.email "[email protected]"
user.password "somepassword"
user.email "[email protected]"
user.password "somepassword"
end
但
Factory.define :user do |user|
user.email "[email protected]"
user.password "somepassword"
end
Factory.define :user do |user|
user.email "[email protected]"
user.password "somepassword"
end
它不起作用 - 属性已定义:电子邮件
。
How do I create multiple records or multiple factories of the same class?
I tried:
Factory.define :user do |user|
user.email "[email protected]"
user.password "somepassword"
user.email "[email protected]"
user.password "somepassword"
end
and
Factory.define :user do |user|
user.email "[email protected]"
user.password "somepassword"
end
Factory.define :user do |user|
user.email "[email protected]"
user.password "somepassword"
end
But it doesn't work -- Attribute already defined: email
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这是一个较旧的问题和答案,但这是我在 Google 上找到的第一个结果,因此我想我应该从 docs 标题下构建或创建多个记录:
如果您想在 Rails 控制台中运行此命令,请在此处考虑以下答案: https://stackoverflow.com/a/23580836/4880924
在我刚刚引用的示例中,每个用户都会有不同的用户名,前提是在工厂定义中使用
sequence
(请参阅上面 Mike Lewis 的回答)。This is an older question and answer but it was the first result I found on Google so I thought I would add the following from the docs under the heading Building or Creating Multiple Records:
If you want to run this in the rails console, consider the following answer here: https://stackoverflow.com/a/23580836/4880924
In the example I just cited, each user would have a different username, provided that
sequence
is used in the factory definition (see Mike Lewis' answer above).如果您希望来自同一(基础)工厂的记录具有不同的值,有几个选项。
A) 覆盖定义的属性
B) 继承
C) 序列
D) 特征
这些方法可以组合。此示例使用列表和对以及序列和覆盖。
我更喜欢尽可能使用特征,我发现它们很灵活。
There's a couple of options if you want records from the same (base) factory to have different values.
A) Override defined attributes
B) Inheritance
C) Sequences
D) Traits
These methods can be combined. This example uses lists and pairs with sequences and overriding.
I prefer to use traits whenever possible, I find them flexible.
使用工厂有两个步骤,第一步是定义它们,第二步是使用它们。
1) 定义它们:
2) 使用它们:
一个例子是在规范中使用它们:
我会观看这个 Railscast 以获得更好的感觉。
There are two steps to using Factories, the first is to define them, and the second is to use them.
1) Define Them:
2) Using Them:
An example would be to use them in a spec:
I'd watch this Railscast to get a better feel for it.
在当前的
factory_girl_rails
4.6.0 中,我遇到了一个与build(:model)
始终返回相同对象实例的问题。使用sequence(:name) ...
并没有解决这个问题。所以我生成了一些像这样的假(空)特征:然后调用 build(:model, :var1), build(:model, :var2)...
With the current
factory_girl_rails
4.6.0 I had the somehow related problem thatbuild(:model)
returned always the same instance of the object. Usingsequence(:name) ...
didn't fix that. So I generated some fake (empty) traits like this:And then calling
build(:model, :var1), build(:model, :var2)...