用户定义的元数据

您可以将用户定义的元数据附加到任何示例组或示例。 将哈希作为最后一个参数(在块之前)传递给 describecontextit。 RSpec 支持许多配置选项,这些选项仅根据元数据应用于某些示例或组。

在示例组上定义的元数据可用于(并且可以被覆盖)任何子组或来自该组或子组中的任何示例。

此外,您可以只使用符号来指定元数据。 作为参数传递给 describecontextit 的每个符号都将是元数据哈希中的一个键,其对应的值为 true

使用哈希定义组元数据

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

RSpec.describe "a group with user-defined metadata", :foo => 17 do
  it 'has access to the metadata in the example' do |example|
    expect(example.metadata[:foo]).to eq(17)
  end

  it 'does not have access to metadata defined on sub-groups' do |example|
    expect(example.metadata).not_to include(:bar)
  end

  describe 'a sub-group with user-defined metadata', :bar => 12 do
    it 'has access to the sub-group metadata' do |example|
      expect(example.metadata[:bar]).to eq(12)
    end

    it 'also has access to metadata defined on parent groups' do |example|
      expect(example.metadata[:foo]).to eq(17)
    end
  end
end

我运行 rspec define_group_metadata_with_hash_spec.rb

那么 示例应该全部通过。

使用哈希定义示例元数据

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

RSpec.describe "a group with no user-defined metadata" do
  it 'has an example with metadata', :foo => 17 do |example|
    expect(example.metadata[:foo]).to eq(17)
    expect(example.metadata).not_to include(:bar)
  end

  it 'has another example with metadata', :bar => 12, :bazz => 33 do |example|
    expect(example.metadata[:bar]).to eq(12)
    expect(example.metadata[:bazz]).to eq(33)
    expect(example.metadata).not_to include(:foo)
  end
end

我运行 rspec define_example_metadata_with_hash_spec.rb

那么 示例应该全部通过。

覆盖用户定义的元数据

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

RSpec.describe "a group with user-defined metadata", :foo => 'bar' do
  it 'can be overridden by an example', :foo => 'bazz' do |example|
    expect(example.metadata[:foo]).to eq('bazz')
  end

  describe "a sub-group with an override", :foo => 'goo' do
    it 'can be overridden by a sub-group' do |example|
      expect(example.metadata[:foo]).to eq('goo')
    end
  end
end

我运行 rspec override_metadata_spec.rb

那么 示例应该全部通过。

更简洁的元数据

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

RSpec.describe "a group with simple metadata", :fast, :simple, :bug => 73 do
  it 'has `:fast => true` metadata' do |example|
    expect(example.metadata[:fast]).to eq(true)
  end

  it 'has `:simple => true` metadata' do |example|
    expect(example.metadata[:simple]).to eq(true)
  end

  it 'can still use a hash for metadata' do |example|
    expect(example.metadata[:bug]).to eq(73)
  end

  it 'can define simple metadata on an example', :special do |example|
    expect(example.metadata[:special]).to eq(true)
  end
end

我运行 rspec less_verbose_metadata_spec.rb

那么 示例应该全部通过。