O'Reilly logo

Effective Testing with RSpec 3 by Myron Marston, Ian Dees

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Isolating Your Specs Using Database Transactions

To solve this issue, we’re going to wrap each spec in a database transaction. After each example runs, we want RSpec to roll back the transaction, canceling any writes that happened and leaving the database in a clean state. Sequel provides a test-friendly method for wrapping code in transactions.[44]

An RSpec around hook would be perfect for this task. You already have a spec/support/db.rb file for database support code, so add it there, inside the RSpec.configure block:

 c.around(​:example​, ​:db​) ​do​ |example|
  DB.transaction(​rollback: :always​) { example.run }
 end

The sequence of calls in the new hook is a bit twisty, so bear ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required