Faker 在factory_girl 中使用时会产生重复数据
我正在尝试使用 Faker gem 将一些虚假数据填充到工厂中:
Factory.define :user do |user|
user.first_name Faker::Name::first_name
user.last_name Faker::Name::last_name
user.sequence(:email) {|n| "user#{n}@blow.com" }
end
但是,虽然我希望这会产生具有不同名字和姓氏的用户,但每个用户都是相同的:
>> Factory(:user)
=> #<User id: 16, email: "[email protected]", created_at: "2011-03-18 18:29:33",
updated_at: "2011-03-18 18:29:33", first_name: "Bailey", last_name: "Durgan">
>> Factory(:user)
=> #<User id: 17, email: "[email protected]", created_at: "2011-03-18 18:29:39",
updated_at: "2011-03-18 18:29:39", first_name: "Bailey", last_name: "Durgan">
How can I get the Faker gem togenerate new names每个用户而不只是重复使用原来的用户?
I'm trying to populate some fake data into a factory using the Faker gem:
Factory.define :user do |user|
user.first_name Faker::Name::first_name
user.last_name Faker::Name::last_name
user.sequence(:email) {|n| "user#{n}@blow.com" }
end
However while I expect this to produce users who have different first_name and last_names, each one is the same:
>> Factory(:user)
=> #<User id: 16, email: "[email protected]", created_at: "2011-03-18 18:29:33",
updated_at: "2011-03-18 18:29:33", first_name: "Bailey", last_name: "Durgan">
>> Factory(:user)
=> #<User id: 17, email: "[email protected]", created_at: "2011-03-18 18:29:39",
updated_at: "2011-03-18 18:29:39", first_name: "Bailey", last_name: "Durgan">
How can I get the Faker gem to generate new names for each users and not just reuse the original ones?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
尝试在伪造者周围加上括号。请参阅此链接
Try putting brackets around the fakers. see this link
请注意,由于可用的虚假数据数量有限,Faker 可能仍在提供重复数据。
为了简单的测试目的并通过唯一性验证,我使用了以下内容:
Note that Faker may still be providing duplicate data due to the limited amount of fake data available.
For simple testing purposes and to get by uniqueness validations, I've used the following:
为了保留正确答案,这里是从博客中转来的,我不承认答案。
为了解释原因,第一个例子是产生相同的名称。只评估一次。第二个示例在每次使用工厂时进行评估。
这是由于
{}
提供了惰性求值。本质上,他们提供了一个 proc/lambda,并以 Faker 调用作为返回值。For the sake of preserving the correct answer, here it is translocated from the blog, I take no credit for the answer.
To explain why, the first example is producing the same names. It's only evaluating once. The second example evaluates every time the factory is used.
This is due to the
{}
providing lazy evaluation. Essentially they are providing a proc/lambda with the Faker call as their return value.当您对属性进行唯一性验证时,使用序列的一种(效率较低)替代方法是检查建议值是否已存在并继续尝试新值,直到它是唯一的:
A (less efficient) alternative to using sequences when you have a uniqueness validation on an attribute is to check whether a proposed value already exists and keep trying new ones until it's unique: