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

Sharing Code Conditionally

In Chapter 7, Structuring Code Examples, we discussed three ways to share code across many example groups:

  • Top-level config hooks
  • Modules containing helper methods
  • Shared contexts containing RSpec constructs (such as hooks and let blocks)

You’ve used all of these techniques throughout this book. By default, they all share code unconditionally. If you define, say, a before hook in your RSpec.configure block, the hook will run for every example.

Often, though, you want to use a certain bit of shared code only for specific examples. For instance, in Isolating Your Specs Using Database Transactions, you defined an around hook to wrap a database transaction around only the examples tagged with :db:

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