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 ...
Get Effective Testing with RSpec 3 now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.