ruby-on-railsrubyrspecruby-on-rails-5ruby-on-rails-6

RSpec Expect Hash to include an Array of key value pairs


Still learning Rspec as a whole, so thanks for patience.

Return value is this:

{ supermodel: {
    'id': 1,
    'name': 'J',
    'model_attributes': [
        {attr1: 'T', attrA: 1}, 
        {attr2: 'F', attrB: 2}, 
        {attr3: 'T', attrC: 3}
        ],
    }
}

Trying to get an expectation that says that a hash key named 'model_attributes' contains a value of an array that includes the following key value pairs - {attr2:F, attrB: 2} and {attr3: T, attrC: 3}.

Any insight would be welcome.


Solution

  • describe 'Stuff' do
      let(:model_attributes) do
        [
          {attr1: 'T', attrA: 1}, 
          {attr2: 'F', attrB: 2}, 
          {attr3: 'T', attrC: 3}
        ]
      end
      let(:result) do
        { supermodel: 
          {
            'id': 1,
            'name': 'J',
            'model_attributes': model_attributes
          }
        }
      end
    
      it 'has the correct model_attributes value' do
        expect(result.dig(:supermodel, :model_attributes)).to eq(model_attributes)
      end
    end