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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With