如何在测试前阻止 rspec 删除测试数据库 [英] How to stop rspec from dropping the test database before tests

查看:48
本文介绍了如何在测试前阻止 rspec 删除测试数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个使用相同数据库的 Rails 应用程序.一个应用程序通过迁移管理数据库,而另一个应用程序只是访问它.

I have two Rails apps that use the same database. One app is managing the database through migrations but the other is just accessing it.

出于某种原因,当我在不管理数据库的应用程序中使用 RSpec 运行测试时,它会在运行测试之前删除数据库.但是因为这个应用程序不知道如何重新创建数据库,所以所有的测试都会失败.

For some reason when I run tests with RSpec in the app that is not managing the database it drops the database before running the tests. But because this app does not know how to recreate the database all tests will fail.

我如何告诉 RSpec 不要删除数据库,直接使用它?

How can I tell RSpec not to drop the database, just use it as it is?

推荐答案

如果不需要迁移数据库可以重新定义rspecs-railsspec:prepare 任务如下:

If you don't need to migrate the database you can redefine rspecs-rails spec:prepare task like this:

lib/tasks/patch_rspec_rails.rb

Rake::Task["spec:prepare"].clear
namespace :spec do
  task :prepare do
    ENV['RACK_ENV'] = ENV['RAILS_ENV'] = 'test'
  end 
end

原始spec:prepare 任务调用test:prepare,它设置了数据库.

The original spec:prepare task callstest:prepare, which setups the db.

任务 test:prepare 存在于 Rails 4.0(或者可能更早).此任务也存在于 Rails 5.0 中.它是 railsties 添加测试相关设置的钩子.您可以使用 rake -W test:prepare 检查其定义.那任务被命中,您可以使用 rake --trace spec 检查.

The task test:prepare exists since Rails 4.0 (or maybe earlier). This task also exists within Rails 5.0. It is a hook for railsties to add test dependent setups. You can check its definition with rake -W test:prepare. That the task is hit you can check with rake --trace spec.

ActiveRecord 使用此任务检查迁移状态并设置数据库.

ActiveRecord uses this task to check the migration state and setup the db.

不调用此任务时,不会删除或创建任何数据库.

When this task is not called, no db will be dropped or created.

但请注意,当其他一些 gem 使用 test:prepare 作为挂钩并插入测试时,它将不起作用.

But be aware, when some other gem uses test:prepare as a hook too plug into tests, it will not work.

从 Rails 4.1 开始,您可以在 config/environments/test.rb 中设置 config.active_record.maintain_test_schema = false.这样,Rails 就不会再尝试迁移您的测试架构.

Since Rails 4.1 you can set config.active_record.maintain_test_schema = false within config/environments/test.rb. This way Rails should no longer try to migrate your test schema.

这篇关于如何在测试前阻止 rspec 删除测试数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆