contain_exactly 匹配器

contain_exactly 匹配器提供了一种方法,可以以不考虑实际数组和预期数组之间排序差异的方式测试数组。例如

  expect([1, 2, 3]).to    contain_exactly(2, 3, 1) # pass
  expect([:a, :c, :b]).to contain_exactly(:a, :c ) # fail

此匹配器也可用作 match_array,它期望预期数组作为单个数组参数而不是作为单独的展开元素给出。上面的内容也可以写成

  expect([1, 2, 3]).to    match_array [2, 3, 1] # pass
  expect([:a, :c, :b]).to match_array [:a, :c]  # fail

数组预期包含所有值

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

RSpec.describe [1, 2, 3] do
  it { is_expected.to contain_exactly(1, 2, 3) }
  it { is_expected.to contain_exactly(1, 3, 2) }
  it { is_expected.to contain_exactly(2, 1, 3) }
  it { is_expected.to contain_exactly(2, 3, 1) }
  it { is_expected.to contain_exactly(3, 1, 2) }
  it { is_expected.to contain_exactly(3, 2, 1) }

  # deliberate failures
  it { is_expected.to contain_exactly(1, 2, 1) }
end

我运行 rspec contain_exactly_matcher_spec.rb

然后输出应包含“7 个示例,1 个失败”

并且输出应包含

     Failure/Error: it { is_expected.to contain_exactly(1, 2, 1) }

       expected collection contained:  [1, 1, 2]
       actual collection contained:    [1, 2, 3]
       the missing elements were:      [1]
       the extra elements were:        [3]

数组预期不包含所有值

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

RSpec.describe [1, 2, 3] do
  it { is_expected.to_not contain_exactly(1, 2, 3, 4) }
  it { is_expected.to_not contain_exactly(1, 2) }

  # deliberate failures
  it { is_expected.to_not contain_exactly(1, 3, 2) }
end

我运行 rspec contain_exactly_matcher_spec.rb

然后输出应包含“3 个示例,1 个失败”

并且输出应包含

     Failure/Error: it { is_expected.to_not contain_exactly(1, 3, 2) }
       expected [1, 2, 3] not to contain exactly 1, 3, and 2