Technical deep-dive

Database transactions in RSpec

Weird things under the hood

Duong Nguyen
The Startup
Published in
4 min readJun 19, 2020

--

Photo by fabio on Unsplash

Stale data between test cases is one of the major causes of race conditions in RSpec. This includes data in databases, Redis, files, …

In this article, we would be focusing on how to clean up stale data in databases.

Rails RSpec default transactions under the hood

If you use rails-rspec, by default, the following config is enabled in spec/rails_helper.rb.

This means “running every example within a transaction”, i.e. all database changes during an example would be rolled-back at the end of that example.

But wait… How can “transactional fixtures” lead to “running every example within a transaction”?

After digging the Rails 4 codebase to see what it really does behind the scene, here is what I found.

Rails calls begin_transaction for every database connection

--

--

Duong Nguyen
The Startup

Engineering Manager@ Rakuten Viki. All opinions are my own.