如何在测试我的应用程序之前自动加载测试数据库中的数据? [英] How to auto-load data in the test database before to test my application?
问题描述
我使用 Ruby on Rails 3.0.9 和 RSpec 2.我想在测试我的应用程序之前自动加载 test 数据库中的种子数据.也就是说,在测试启动时(当我运行测试时)我想自动填充"\自动启动"测试数据库.
I am using Ruby on Rails 3.0.9 and RSpec 2. I would like to auto-load seed data in the test database before I tesst my application. That is, at the testing start up time (when I run tests) I would like to "auto-populate"\"auto-boot" the test database.
如何用种子数据填充数据库?
PS:当我阅读时,(也许)我应该通过向 /spec/spec_helper.rb
文件添加一些代码来填充测试数据库......但是什么代码以及怎么做?
P.S.: As I read around, (maybe) I should populate the test database by adding some code to the /spec/spec_helper.rb
file... but what code and how?
在我的 task/custom.rake
文件中,我有:
In my task/custom.rake
file I have:
namespace :test do
desc "Boot database"
task :boot => [:load, :seed] do
end
desc "Reboot database"
task :reboot => [:purge, :boot] do
end
end
推荐答案
如果你只想调用种子耙任务,我会这样做:
If you'd like to just invoke the seed rake task, I'd do something like this:
ENV['RAILS_ENV'] = 'test'
Rake::Task["db:seed"].invoke
但是,我建议使用 Fixtures (http://guides.rubyonrails.org/testing.html#the-low-down-on-fixtures).
But, I'd recommend using Fixtures (http://guides.rubyonrails.org/testing.html#the-low-down-on-fixtures).
或者甚至是像 Factory Girl (https://github.com/thoughtbot/factory_girl) 这样的夹具替代品,您可以加载带有所有关联数据的虚拟数据.这是一种不那么脆弱的方法.
Or even better a fixture replacement like Factory Girl (https://github.com/thoughtbot/factory_girl), whereby you can load dummy data with all the associated data. This is a much less brittle approach.
这篇关于如何在测试我的应用程序之前自动加载测试数据库中的数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!