Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Before and After hooks for a spec directory in RSpec

We have quite a bit of tests in our RSpec test suite. directory structure looks something like -

spec/
  truncation/
    example1_spec.rb
    example2_spec.rb
    ...
  transaction/
    example1_spec.rb
    example2_spec.rb
    ...

I wanted to restore a test database dump, before all of the spec files in transaction/ folder are run and empty it after all tests finish.

Is there a way to do this?

There are before(:suite) and after(:suite) hooks but these work for individual spec files.

Is there a way to provide before and after hooks for directories in RSpec?

like image 576
Optimus Avatar asked Apr 15 '15 13:04

Optimus


1 Answers

Are you using RSpec 3+?

You can use #define_derived_metadata to add custom metadata based on file path matchers.

RSpec.configure do |config|
  config.define_derived_metadata(file_path: %r{spec/truncation}) do |metadata|
    metadata[:truncation] = true
  end

  config.before(:all, :truncation) do
    # truncate that bad boy
  end
end

This is the same method used in rspec-rails to add custom behavior to specs in the specific directories, e.g. spec/controllers.

Docs

like image 192
rossta Avatar answered Sep 26 '22 23:09

rossta