Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RSpec: How to test existence of keys in an array of hashes?

I have a class:

class ApiParser
  def initialize
    ..
  end

  def api_data
    # returns an array of hashes like so:
    # [{ answer: "yes", name: "steve b" age: 22, hometown: "chicago", ... },
    # { answer:"unsure", name: "tom z", age: 44, hometown: "baltimore" , ... },
    # { answer: "no", name: "the brah", age: nil, hometown: "SF", ... }, 
    # { ... }, { ... }, ... ]
  end
end

The method returns an array of hashes. The length of the array is 50 elements.

Each hash has the exact same keys. There are around 20 keys.

I am not sure what would be the best way to unit test this method. How can I check that the method is indeed returning an array with each hash having these keys? Some of the hash values may be nil, so I do not think I will test the values.

like image 708
user3809888 Avatar asked Oct 28 '25 10:10

user3809888


1 Answers

This will help:

describe "your test description" do
  let(:hash_keys) { [:one, :two].sort } # and so on

  subject(:array) { some_method_to_fetch_your_array }

  specify do
    expect(array.count).to eq 50

    array.each do |hash|
      # if you want to ensure only required keys exist
      expect(hash.keys).to contain_exactly(*hash_keys)
      # OR if keys are sortable
      # expect(hash.keys.sort).to eq(hash_keys)

      # if you want to ensure that at least the required keys exist
      expect(hash).to include(*hash_keys)
    end
  end
end

One problem with that approach: if the test fails, you'll have trouble finding out exactly which array index caused the failure. Adding a custom error message will help. Something like the following:

array.each_with_index do |hash, i|
  expect(hash.keys).to contain_exactly(*hash_keys), "Failed at index #{i}"
end
like image 51
SHS Avatar answered Oct 30 '25 03:10

SHS



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!