创建“测试”的最佳方法是什么? >= Rails 3.2.0 中的数据库内容?

发布于 2025-01-02 00:21:23 字数 266 浏览 0 评论 0原文

我希望能够创建几十个用户、文章(或应用程序特有的任何资源)等,以查看应用程序在充满时的外观和响应。这仅用于测试/开发目的,所以我希望能够轻松地回滚、销毁它或进行其他操作。也许是我想多了,谁知道呢。

我看到人们建议只使用标准迁移,这是一个想法,但我想选择性地执行此操作,我不希望项目中的每个人在更新应用程序时获取示例内容。

其他人提到了“工厂女孩”,但这看起来可能要么是矫枉过正,要么是真正为测试而设计的宝石的副用,等等。目前还不太清楚。

那么遇到这种情况大家都怎么办呢?

I want to be able to create a few dozen users, articles (or whatever resources are unique to the app), etc to see how the app looks and responds when full. This is just for testing/dev purposes, so I want to be able to roll it back, destroy it, or whatever easily. Perhaps I'm overthinking it, who knows.

I've seen people recommend just using a standard migration, which is one idea, but I want to do this OPTIONALLY, I don't want everyone on the project to get the sample content as they update the app.

Other people have mentioned Factory Girl, but that looks like it might be either overkill or a side-use of a gem really designed for testing, etc. It wasn't perfectly clear.

So what do you all do in this case?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(2

柒夜笙歌凉 2025-01-09 00:21:23

我推荐一个 rake 任务。您可以将它放在 lib/tasks 中,这样项目中的每个人都可以获取它,但不是每个人都需要运行它,只有当它运行时它才会执行任何操作。 这是一个关于编写 rake 任务的很棒的教程,只需记住阅读下面的部分Rails 标题,以了解如何引入模型。

之后,您的 rake 任务基本上只是 ruby​​ 代码。我建议使用动态 find_or_create_by 方法来显式创建所需的模型,如果运行多次,则不会多次创建它们。您还可以选择在创建特定模型中的所有记录之前将其销毁。

我不建议使用 Factory Girl,因为您可能希望明确控制模型的创建方式。

下面是一个示例 rake 任务,展示了它是多么简单:

#lib/tasks/my_task.rake
task :fake_data => :environment do
    MyModel.find_or_create_by_name("Test")
end

然后在你的控制台中:

rake fake_data

或者:

rake fake_data RAILS_ENV=test

Ta da!

I recommend a rake task. You can stick it in lib/tasks and so everyone in the project gets it, but not everyone needs to run it, and only when it's run will it do anything. This a great tutorial on writing rake tasks, just remember to read the part under the Rails heading in order to learn how to bring in your models.

After that, your rake tasks is basically just ruby code. I'd suggest using the dynamic find_or_create_by methods in order to explicitly create the models you want, and if it's run multiple times, they won't be created multiple times. You can also choose to destroy all records in a particular model before creating them.

I wouldn't recommend using Factory Girl because you probably want explicit control over how your models are created.

Here's an example rake task to show how easy it is:

#lib/tasks/my_task.rake
task :fake_data => :environment do
    MyModel.find_or_create_by_name("Test")
end

Then in your console:

rake fake_data

Or:

rake fake_data RAILS_ENV=test

Ta da!

怂人 2025-01-09 00:21:23

查看 Rails 种子数据功能

http://railscasts.com/episodes/179-seed-data

Take a look at Rails seed data features

http://railscasts.com/episodes/179-seed-data

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