使用 filter_run_when_matching

您可以使用 config.filter_run_when_matching 配置一个条件过滤器,该过滤器仅在存在任何匹配的示例时才适用。这通常用于焦点过滤

  RSpec.configure do |c|
    c.filter_run_when_matching :focus
  end

此配置允许您通过使用 :focus 元数据标记它们来过滤到特定示例或组。当没有示例或组处于焦点状态(这应该是规范,因为它旨在成为临时更改)时,过滤器将被忽略。

RSpec 还提供别名——fitfdescribefcontext——作为 itdescribecontext 的简写,带有 :focus 元数据,使您可以轻松地通过在前面加上 f 来暂时聚焦示例或组。

背景

假设有一个名为“spec/spec_helper.rb”的文件,内容如下

RSpec.configure do |c|
  c.filter_run_when_matching :focus
end

并且有一个名为“.rspec”的文件,内容如下

--require spec_helper

并且有一个名为“spec/example_spec.rb”的文件,内容如下

RSpec.describe "A group" do
  it "has a passing example" do
  end

  context "a nested group" do
    it "also has a passing example" do
    end
  end
end

当没有内容处于焦点状态时,过滤器将被忽略

我运行 rspec --format doc

那么它应该通过,显示“2 个示例,0 个失败”

并且输出应该包含

A group
  has a passing example
  a nested group
    also has a passing example

示例可以使用 fit 聚焦

假设我在“spec/example_spec.rb”中将 it "has a passing example" 更改为 fit "has a passing example"

我运行 rspec --format doc

那么它应该通过,显示“1 个示例,0 个失败”

并且输出应该包含

A group
  has a passing example

组可以使用 fdescribefcontext 聚焦

假设我在“spec/example_spec.rb”中将 context 更改为 fcontext

我运行 rspec --format doc

那么它应该通过,显示“1 个示例,0 个失败”

并且输出应该包含

A group
  a nested group
    also has a passing example