What is an efficient way to test that a hash contains specific keys and values?
By efficient I mean the following items:
- easy to read output when failing
- easy to read source of test
- shortest test to still be functional
Sometimes in Ruby I must create a large hash. I would like to learn an efficient way to test these hashes:
expected_hash = {
:one => 'one',
:two => 'two',
:sub_hash1 => {
:one => 'one',
:two => 'two'
},
:sub_hash2 => {
:one => 'one',
:two => 'two'
}
}
I can test this has several ways. The two ways I use the most are the whole hash at once, or a single item:
assert_equal expected_hash, my_hash
assert_equal 'one', my_hash[:one]
These work for small hashes like our example hash, but for a very large hash these methods break down. The whole hash test will display too much information on a failure. And the single item test would make my test code too large.
I was thinking an efficient way would be to break up the tests into many smaller tests that validated only part of the hash. Each of these smaller tests could use the whole hash style test. Unfortunately I don’t know how to get Ruby to do this for items not in a sub-hash. The sub-hashes can be done like the following:
assert_equal expected_hash[:sub_hash1], my_hash[:sub_hash1]
assert_equal expected_hash[:sub_hash2], my_hash[:sub_hash2]
How do I test the remaining parts of the hash?
When testing, you need to use manageable chunks. As you found, testing against huge hashes makes it difficult to track what is happening.
Consider converting your hashes to arrays using
to_a. Then you can easily use the set operators to compare arrays, and find out what is missing/changed.For instance: