Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 4: How to reset test database?

I'm on Rails 4 and have noticed some of my RSpec tests are failing because some of my test refactorings use a before filter (presumably because of transactions). This post describes a similar issue:

rails test database not clearing after some runs

In lieu of using the DatabaseCleaner gem, is there a rake command to clear out the test database? I believe rake db:test:prepare is deprecated in Rails 4. Also, if before transactions like

`post :create, user: Fabricate.attributes_for(:user)` 

are persistent, is there an alternative way of refactoring to avoid the need to manually clear out the test database?

like image 925
Solomons_Ecclesiastes Avatar asked Sep 16 '14 20:09

Solomons_Ecclesiastes


People also ask

How do I reset my rails database?

You can use db:reset - for run db:drop and db:setup or db:migrate:reset - which runs db:drop, db:create and db:migrate.

What does Rails DB Reset do?

db:reset: Resets your database using your migrations for the current environment. It does this by running the db:drop , db:create , db:migrate tasks. db:rollback: Rolls the schema back to the previous version, undoing the migration that you just ran. If you want to undo previous n migrations, pass STEP=n to this task.

What is rake db test prepare?

The rake db:test:load recreates the test database from the current db/schema. rb. On subsequent attempts, it is a good idea to first run db:test:prepare, as it first checks for pending migrations and warns you appropriately.


1 Answers

An overkill solution would be:

bundle exec rake db:drop RAILS_ENV=test bundle exec rake db:create RAILS_ENV=test bundle exec rake db:schema:load RAILS_ENV=test 

You could make this all in a rake task and run that.

Another solution from here is to include the following your spec_helper.rb file

config.after :all do   ActiveRecord::Base.subclasses.each(&:delete_all) end 

Disclaimer: I have not tested this and you should read the SO post as it may not work in all situations.

That being said, I would recommend using the database cleaner gem to avoid situations such as this.

like image 120
ChrisBarthol Avatar answered Sep 19 '22 18:09

ChrisBarthol