--example 选项

使用 --example(或 -e)选项按名称过滤示例。

该参数与示例的完整描述匹配,该描述是组(包括任何嵌套组)和示例的描述的串联。

这使您能够运行单个唯一命名的示例、所有具有类似名称的示例、唯一命名的组中的所有示例等。

您还可以多次使用该选项以指定多个示例匹配项。

注意:没有描述的示例具有生成的描述(在使用 单行语法 时很常见),不能直接使用此选项过滤,因为必须执行示例才能生成描述,因此 RSpec 无法使用尚未生成的描述来决定是否执行示例。当然,您可以传递组描述的一部分来选择组中定义的所有示例(包括那些没有描述的示例)。

背景

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

RSpec.describe "first group" do
  it "first example in first group" do; end
  it "second example in first group" do; end
end

以及一个名为“second_spec.rb”的文件,其中包含

RSpec.describe "second group" do
  it "first example in second group" do; end
  it "second example in second group" do; end
end

以及一个名为“third_spec.rb”的文件,其中包含

RSpec.describe "third group" do
  it "first example in third group" do; end
  context "nested group" do
    it "first example in nested group" do; end
    it "second example in nested group" do; end
  end
end

以及一个名为“fourth_spec.rb”的文件,其中包含

RSpec.describe Array do
  describe "#length" do
    it "is the number of items" do
      expect(Array.new([1,2,3]).length).to eq 3
    end
  end
end

没有匹配项

我运行 rspec . --example nothing_like_this

那么进程应成功,即使没有运行任何示例。

匹配一个词

我运行 rspec . --example example

那么示例应全部通过。

每个上下文中一个匹配项

我运行 rspec . --example 'first example'

那么示例应全部通过。

在一个文件中使用示例名称进行一个匹配项

我运行 rspec . --example 'first example in first group'

那么示例应全部通过。

在一个文件中使用示例名称和组名称进行一个匹配项

我运行 rspec . --example 'first group first example in first group'

那么示例应全部通过。

一个组中的所有示例

我运行 rspec . --example 'first group'

那么示例应全部通过。

在一个文件中使用组名称进行一个匹配项

我运行 rspec . --example 'second group first example'

那么示例应全部通过。

一个组中的所有示例,包括嵌套组中的示例

我运行 rspec . --example 'third group'

那么示例应全部通过。

使用 ClassName#method_name 形式进行匹配

我运行 rspec . --example 'Array#length'

那么示例应全部通过。

示例名称选项的多次应用

我运行 rspec . --example 'first group' --example 'second group' --format d

那么示例应全部通过

以及输出应包含以下所有内容

first example in first group
second example in first group
first example in second group
second example in second group

以及输出不应包含以下任何内容

first example in third group
nested group first example in nested group
nested group second example in nested group