RSpec 中规范目录的前后挂钩

Before and After hooks for a spec directory in RSpec

我们的 RSpec 测试套件中有很多测试。目录结构类似于 -

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

我想恢复一个测试数据库转储,然后 transaction/ 文件夹中的所有规范文件都 运行 并在所有测试完成后清空它。

有办法吗?

before(:suite)after(:suite) 挂钩,但这些挂钩适用于单个规范文件。

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

您在使用 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

这是在 rspec-rails 中使用的 same method,用于向特定目录中的规范添加自定义行为,例如spec/controllers.

Docs