使用 when_first_matching_example_defined 钩子

在使用 RSpec 的大型项目中,通常会有一些昂贵的设置逻辑,这些逻辑仅在加载某些类型的规范时才需要。如果尚未加载这种类型的规范,则最好避免执行设置的成本。

when_first_matching_example_defined 钩子使您可以轻松地根据第一个定义的具有匹配元数据的示例有条件地执行一些逻辑,从而确保仅在需要时才执行必要的设置。

背景

给定一个名为“spec/spec_helper.rb”的文件,其中包含

RSpec.configure do |config|
  config.when_first_matching_example_defined(:db) do
    require "support/db"
  end
end

并且一个名为“spec/support/db.rb”的文件,其中包含

RSpec.configure do |config|
  config.before(:suite) do
    puts "Bootstrapped the DB."
  end

  config.around(:example, :db) do |example|
    puts "Starting a DB transaction."
    example.run
    puts "Rolling back a DB transaction."
  end
end

并且一个名为“.rspec”的文件,其中包含

--require spec_helper

并且一个名为“spec/unit_spec.rb”的文件,其中包含

RSpec.describe "A unit spec" do
  it "does not require a database" do
    puts "in unit example"
  end
end

并且一个名为“spec/integration_spec.rb”的文件,其中包含

RSpec.describe "An integration spec", :db do
  it "requires a database" do
    puts "in integration example"
  end
end

运行整个套件将加载 DB 设置

我运行 rspec

那么它应该通过,并显示

Bootstrapped the DB.
Starting a DB transaction.
in integration example
Rolling back a DB transaction.
.in unit example
.

仅运行单元规范不会加载 DB 设置

我运行 rspec spec/unit_spec.rb

那么所有示例都应该通过

并且输出不应包含“DB”。