RSpec and DatabaseCleaner: Using different cleaning strategy per example

Sometimes you need to use different cleaning strategy for particular test example than transaction. But setting deletion or truncation for whole test suite could result in huge slowdown. Here’s how to solve it:

Usually you have something like this in your spec/rails_helper.rb file:

As you may see there is example objected passed to the around hook of rspec. This object looks like regular Proc object pointing to the example test block. But it actually carry some meta information about the example itself and it’s context in example.metadata value, like name, test description, test file, etc.

Simply we could just match test name against tests we want to use different strategy and set it for them. But it would not be so DRY. Fortunately, RSpec allows to specify custom parameters for each example, context, describe block and so, that are inherited by test hierarchy. Lets use it for setting specific cleaning strategy:

and change around hook configuration of DatabaseCleaner:

Happy testing! :)