Testing Hash Contents Using Rspec

Testing hash contents using RSpec

It works for hashes too:

expect(jump_locations).to include(
"upper_left" => true,
"upper_right" => false,
"lower_left" => false,
"lower_right" => true
)

Source:
include matcher @ relishapp.com

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

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

writing a rspec test for checking a function that returns a hash table

The problem seems to be that ruby is interpreting your expected hash:

expect(game.location_counts(black_queen)).to be {"4, 4"=>2, "1, 1"=>1}

as a block passed to the be method, instead of as a parameter. Try the following:

expect(game.location_counts(black_queen)).to eq({"4, 4"=>2, "1, 1"=>1})

or even removing the curly braces, as the hash is the last parameter passed to the be method:

expect(game.location_counts(black_queen)).to eq("4, 4"=>2, "1, 1"=>1)

EDIT: Regard the usage of eq instead of be.

Testing method that needs to sort hash by value in RSpec

That's because the hashes are the same, see this post. Hashes don't really have a concept of order, when you call the sort_by method it is converting the data to an array, ordering the array, and then returning an array. If you are converting the array to a hash you will lose the order essentially.

If you care about the order here, remove the to_h and just deal with the data as an array instead. Then your tests should work.

You can use .to_a in the test, and you don't need reverse in the sort.

view_counter.sort_by { |route, length| -length }

let(:result) do
{
"/help_page/1" => 3,
"/about/2" => 1,
"/contact" => 1,
"/home" => 1,
"/index" => 2,
}.to_a
end

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

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


Related Topics



Leave a reply



Submit