在RSpec中为spec目录挂钩之前和之后

Opt*_*mus 6 ruby rspec ruby-on-rails

我们的RSpec测试套件中有相当多的测试.目录结构看起来像 -

spec/
  truncation/
    example1_spec.rb
    example2_spec.rb
    ...
  transaction/
    example1_spec.rb
    example2_spec.rb
    ...
Run Code Online (Sandbox Code Playgroud)

我希望在transaction/运行文件夹中的所有规范文件之前恢复测试数据库转储,并在所有测试完成后将其清空.

有没有办法做到这一点?

before(:suite)after(:suite)钩子,但这些适用于单个spec文件.

有没有办法为RSpec中的目录提供前后挂钩?

ros*_*sta 9

你在使用RSpec 3+吗?

您可以使用#define_derived_metadata基于文件路径匹配器添加自定义元数据.

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
Run Code Online (Sandbox Code Playgroud)

用于rspec-rails向特定目录中的规范添加自定义行为的方法相同,例如spec/controllers.

文件