Rspec. When hashes are used inside arrays

I'm always amazed at the flexibility of unit testing when working with Ruby projects. Below are examples of such flexibility in which you can check the contents of hashes nested in an array.

context 'when hashes in array' do
  let(:hash_set) do
    [
      { attr1: 1, attr2: 2 },
      { attr1: 3, attr2: 4 }
    ]
  end

  let(:attribute_keys) { %i[attr1 attr2] }

  it 'contains a set of attribute keys' do
    expect(hash_set).to all(include(*attribute_keys))
  end
end

context 'when hashes in nested array' do
  let(:hash_set) do
    [
      { attr1: 1, attr2: [{ attr3: 3, attr4: 4 }] },
      { attr1: 5, attr2: [{ attr3: 6, attr4: 7 }] }
    ]
  end

  let(:first_attribute_keys) { %i[attr1 attr2] }
  let(:second_attribute_keys) { %i[attr3 attr4] }

  it 'contains a set of first attribute keys' do
    expect(hash_set).to all(include(*first_attribute_keys))
  end

  it 'contains a set of second attribute keys' do
    expect(hash_set).to all(
      include(attr2: all(include(*second_attribute_keys)))
    )
  end
end

# Some class for testing
class Tester
  def exec(options)
    # some work
  end
end

context 'when hashes are passed as parameters' do
  subject(:tester) { Tester.new }

  let(:options) do
    {
      attr1: 1,
      attr2: { attr4: 2 },
      attr3: [
        { attr5: 3 },
        { attr6: 4 }
      ]
    }
  end

  it 'contains a set of attribute keys with values' do
    expect(tester).to receive(:exec).with(
      hash_including(
        attr1: 1,
        attr2: hash_including(attr4: 2),
        attr3: [hash_including(attr5: 3), hash_including(attr6: 4)]
      )
    )

    tester.exec(options)
  end

  it 'contains a set of attribute keys' do
    expect(tester).to receive(:exec).with(
      hash_including(
        :attr1,
        attr2: hash_including(:attr4),
        attr3: array_including(hash_including(:attr5), hash_including(:attr6))
      )
    )

    tester.exec(options)
  end
end

No comments :

Post a Comment