Delete all MySQL records while keeping the database schema

Posted About 13 years ago. Visible to the public.

You will occasionally need to clean out your database while keeping the schema intact, e.g. when someone inserted data in a migration or when you had to kill -9 a frozen test process.

Old Capybara versions already have the Database Cleaner gem Show archive.org snapshot as dependency. Otherwise add database_cleaner to your *Gemfile`. This lets you say this from the Rails console:

DatabaseCleaner.strategy = :truncation
DatabaseCleaner.clean

You can package this into a nice little Rake task by copying the attachment into lib/tasks/clean_database.rake. Now you can e.g. clean the test database by saying on the shell:

rake db:clean RAILS_ENV=test

If you are using the parallel_tests gem, the task is aware and will clean all your test databases.

Henning Koch
Last edit
About 7 years ago
Attachments
Keywords
database, clear
License
Source code in this card is licensed under the MIT License.
Posted by Henning Koch to makandra dev (2011-03-14 10:08)