whistler whistler - 1 year ago 73
Ruby Question

Difference between truncation, transaction and deletion database strategies

What is the difference between truncation, transaction and deletion database strategies when using Rspec? I can't find any resources explaining this. I read the Database Cleaner readme but it doesn't explain what each of these do.

Why do we have to use truncation strategy for Capybara? Do I have to clean up my database when testing or can I disable it. I dont understand why I should clean up my database after each test case, wouldn't it just slow down testing?

Answer Source

The database cleaning strategies refer to database terminology. I.e. those terms come from the (SQL) database world, so people generally familiar with database terminology will know what they mean.

The examples below refer to SQL definitions. DatabaseCleaner however supports other non-SQL types of databases too, but generally the definitions will be the same or similar.


This means the database tables are cleaned using a delete + recreate strategy. In SQL this means using the DROP TABLE + CREATE TABLE statements. This strategy would be considered the slowest, since you have to not only delete the table data, but also the whole table structure and then recreate it back. However in case of problems with other methods this can be considered the safest fallback method.

Another option for deletion is simply using DELETE FROM. However this is still slower than truncation, but may have other advantages instead.


This means the database tables are cleaned using the SQL TRUNCATE TABLE command. This will simply empty the table immediately, without deleting the table structure itself.


This means using BEGIN TRANSACTION statements coupled with ROLLBACK to roll back a sequence of previous database operations. Think of it as an "undo button" for databases. I would think this is the most frequently used cleaning method, and probably the fastest since changes need not be directly committed to the DB.

Example discussion: Rspec, Cucumber: best speed database clean strategy

Reason for truncation strategy with Capybara

The best explanation was found in the Capybara docs themselves:

# Transactional fixtures do not work with Selenium tests, because Capybara
# uses a separate server thread, which the transactions would be hidden
# from. We hence use DatabaseCleaner to truncate our test database.

Cleaning requirements

You do not necessarily have to clean your database after each test case. However you need to be aware of side effects this could have. I.e. if you create, modify, or delete some records in one step will the other steps be affected by this?

Normally RSpec runs with transactional fixtures turned on, so you will never notice this when running RSpec - it will simply keep the database automatically clean for you: