如何使用 Factory Girl 和 random_data 通过 Seed.rb 正确随机化数据?

发布于 2025-01-03 13:06:02 字数 995 浏览 0 评论 0原文

我通过尝试使用一个简单的脚本填充我的数据库来第一次生成测试数据,该脚本为我的模型创建足够数量的记录,以考虑所有依赖项(尤其是多态性)。

这是我的 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

并安 2025-01-10 13:06:02

所以我不确定 Random 类来自这里。但我总是使用 Faker gem 来处理这些东西。

它包含姓名、电子邮件、城市、电话号码:像这样:

Faker::Name.name
Faker::Address.uk_country
Faker::Lorem.paragraph

检查一下

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:

Faker::Name.name
Faker::Address.uk_country
Faker::Lorem.paragraph

check it out

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文