ruby 对于RSpec,contain_exactly的hash等价物是什么?

83qze16e  于 2023-05-28  发布在  Ruby
关注(0)|答案(1)|浏览(129)

我需要验证哈希的内容,我惊讶地发现RSpec的contain_exactly只适用于数组。理想的期望是:

expect(type.values.values).to contain_exactly(
  ONE: an_object_having_attributes(value: 'uno'),
  TWO: an_object_having_attributes(value: 'dos')
)

基本要求是contain_exactly要求数组只包含这些元素,并且哈希等价物必须只包含指定的确切键/值对。
有很多解决方法都很好:

  • include(key: value),但这允许其他键,我需要一个完全匹配。
  • expect(hash.keys).to contain_exactly(...),但这并不能验证键是否专门链接到值。
  • 无论如何使用contain_exactly(其将散列读取为[key, value]的元组)并且基于子阵列进行匹配,例如contain_exactly(a_collection_containing_exactly('ONE', an_object_having_attributes(value: 'uno')), ...)
  • 使用aggregate_failures迭代哈希并基于预期输入将键与值进行匹配。

但我最好奇的是是否有一个内置的RSpec方法来做到这一点。

fquxozlt

fquxozlt1#

您可以像这样使用match匹配器

require "ostruct"

describe do
  let(:hash) do
    {
      one: OpenStruct.new(x: 1),
      two: OpenStruct.new(y: 2)
    }
  end

  it "matches hashes" do
    expect(hash).to match(
      two: an_object_having_attributes(y: 2),
      one: an_object_having_attributes(x: 1)
    )
  end

  it "requires the actual to have all elements of the expected" do
    expect(a: 1, b: 2).not_to match(b: 2)
  end

  it "requires the expected to have all elements of the actual" do
    expect(a: 1).not_to match(a: 1, b: 2)
  end
end

如果其中一个散列有额外的键--测试将失败

相关问题