Search code examples
rubyhashrspec

How to test with Rspec that a key exists inside a hash that contains an array of hashes


I have a Model method that returns the following when executed.

 {"data" => [
 {"product" => "PRODUCTA", "orders" => 3, "ordered" => 6, "revenue" => 600.0},
 {"product" => "PRODUCTB", "orders" => 1, "ordered" => 5, "revenue" => 100.0}]}

I would like to test to make sure that "revenue" in the first hash is there and then test that the value is equal to 600.

subject { described_class.order_items_by_revenue }

it "includes revenue key" do
  expect(subject).to include(:revenue)
end

I am completely lost on how to test this with Rspec.


Solution

  • RSpec allows you to use the have_key predicate matcher to validate the presence of a key via has_key?, like so:

    subject { described_class.order_items_by_revenue }
    
    it "includes revenue key" do
      expect(subject.first).to have_key(:revenue)
    end