How to stop rspec from dropping the test database before tests

rspec, ruby-on-rails

Solution

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

The original `spec:prepare` task calls`test:prepare`, which setups the db.

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 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.

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

Edit:

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.

Problem

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. 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. How can I tell RSpec not to drop the database, just use it as it is?

Original source