如何使用 Factory Girl 和 random_data 通过 Seed.rb 正确随机化数据?
我通过尝试使用一个简单的脚本填充我的数据库来第一次生成测试数据,该脚本为我的模型创建足够数量的记录,以考虑所有依赖项(尤其是多态性)。
这是我的 seeds.rb
require 'factory_girl_rails'
50.times do
@user = FactoryGirl.create(:user)
FactoryGirl.create(:contact, :user => @user)
@question = FactoryGirl.create(:question, :user => @user)
FactoryGirl.create(:user_answer, :question => @question, :authorable => @user)
@contact = FactoryGirl.create(:contact, :user => @user)
FactoryGirl.create(:contact_answer, :question => @question, :authorable => @contact)
end
作为示例,这里是 question
工厂:
FactoryGirl.define do
factory :question do
title "What is the best place to travel in " + Random.country + "?"
body Random.paragraphs(2)
association :user, :method => :build
end
end
虽然 Random
类确实生成 一个 随机术语,该术语对于创建的所有实例保持不变。在这种情况下,我会收到 50 个问题,比如“西班牙最好的旅游地点是哪里?”以及每段相同的两段文字。
我缺少什么?
I gave generating test data a first shot by trying to populate my database with a simple script that creates a sufficient number of records for my models accounting for all dependencies (esp. polymorphism).
This is my seeds.rb
require 'factory_girl_rails'
50.times do
@user = FactoryGirl.create(:user)
FactoryGirl.create(:contact, :user => @user)
@question = FactoryGirl.create(:question, :user => @user)
FactoryGirl.create(:user_answer, :question => @question, :authorable => @user)
@contact = FactoryGirl.create(:contact, :user => @user)
FactoryGirl.create(:contact_answer, :question => @question, :authorable => @contact)
end
As an example, here ist the question
factory:
FactoryGirl.define do
factory :question do
title "What is the best place to travel in " + Random.country + "?"
body Random.paragraphs(2)
association :user, :method => :build
end
end
While the Random
class does produce one random term, that term remains the same for all instances created. In this case I would get 50 questions of, say, "What is the best place to travel in Spain?" and the identical two paragraphs of text for each.
What am I missing?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
所以我不确定
Random
类来自这里。但我总是使用 Faker gem 来处理这些东西。它包含姓名、电子邮件、城市、电话号码:像这样:
检查一下
So I'm not sure where the
Random
class is coming from here. But I always used the Faker gem for this stuff.It does names, emails, cities, phone numbers: like this:
check it out