Techioz Blog

RSpec の contains_exactly に相当するハッシュは何ですか?

概要

ハッシュの内容を検証する必要があるのですが、RSpec の contains_exactly が配列に対してのみ機能することに驚きました。理想的な期待値は次のとおりです。

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

基本的な要件は、contain_exactly では配列にそれらの要素のみが含まれることを要求し、同等のハッシュには指定された正確なキーと値のペアのみが含まれている必要があるということです。

問題ない回避策はたくさんあります。

などですが、私が最も興味があるのは、これを行うための組み込みの RSpec 方法があるかどうかです。

解決策

このようにマッチマッチャーを使用できます

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

このハッシュのいずれかに余分なキーがある場合、テストは失敗します