Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test that hash contains specific keys and that values for those keys are not nil

Tags:

ruby

rspec

How can I test that a method returns a hash that contains specific keys and the values for those keys are not nil using RSpec?

like image 837
bimbom22 Avatar asked Nov 12 '11 20:11

bimbom22


People also ask

What is returned if you pass a key that doesnt exist into a hash?

Typically when an element is passed into a hash with no matching key, the hash returns nil .

What is a Ruby hash?

A Hash is a dictionary-like collection of unique keys and their values. Also called associative arrays, they are similar to Arrays, but where an Array uses integers as its index, a Hash allows you to use any object type. Hashes enumerate their values in the order that the corresponding keys were inserted.


1 Answers

I'd write:

describe MyObject do
  describe "#my_method" do
    subject(:my_method) { MyObject.new.my_method }

    it { is_expected.to be_a_kind_of(Hash) }
    specify { expect(my_method.keys).to include(:key1, :key2) }
    specify { expect(my_method.values).not_to include(nil) }
  end
end

It may happen that you have to use keys in inverted commas "key1", "key2". Otherwise it may throw error.

like image 58
tokland Avatar answered Oct 16 '22 14:10

tokland