You need to find a way to clean your database before each spec runs.
There are two common approaches to solve this problem:
- Run every spec inside a transaction
- Truncate all tables before (or after) every spec
However, if you happen to use PostgreSQL, there is another option:
Dropping the database and creating it again from a template.
While this sounds slow and expensive, because of the way PostgreSQL handles templates, it's actually pretty fast.
On my test suite, this is what I usually do:
Before all specs
- Make sure an empty database called 'test_template' exists.
- Dump my development database's schema and populate the test_template database with it. Now 'test_template' is effectively an empty copy of your development database.
# drop database psql -c "DROP DATABASE IF EXISTS test_template" postgres # create database psql -c "CREATE DATABASE test_template WITH OWNER test_user" postgres # dump dev db schema and pipe to test_template # make sure your test user is the one who creates the new tables # (that way he has implicit permissions to access them) pg_dump -s --clean dev_db_name | PGPASSWORD=test_password psql -h localhost -U test_user test_template**Note you can ignore the before all steps if you keep the test_template schema in sync with your dev db schema
Before each spec
- Drop the 'test' database (if it exists)
- Create the 'test' database from the 'test_template'
# drop test database DROP DATABASE IF EXISTS test; # create test database from test_template CREATE DATABASE test TEMPLATE test_template;
Now you can run your specs in a clean environment without compromising on speed.