Skip to content

Instantly share code, notes, and snippets.

@mathie
Created April 29, 2010 08:55
Show Gist options
  • Save mathie/383342 to your computer and use it in GitHub Desktop.
Save mathie/383342 to your computer and use it in GitHub Desktop.

Hash ordering test

This test passes on my system right now. (It might not on your system, but that's not important. Change the assert_equal so that it does.)

Now uncomment the @other_hash declaration. It (probably) fails.

That makes the hashing algorithm in Ruby dependent upon the code that runs before it. Which, when you accidentally depend upon the order of keys in a hash, makes for a lot of confusion later on when it no longer works!

The particular example involved verifying that a model accepted nested attributes. We were doing something along the lines of:

model = Factory.build(:model,
  :nested_model => nil, # override the default factory association
  :nested_model_attributes => Factory.attributes_for(:nested_model)
)

That worked when it was first coded. But when we introduced another completely unrelated test in a completely different shoulda context, it broke. To much head-scratching last night!

require 'test/unit'
class HashTest < Test::Unit::TestCase
def setup
# @other_hash = {
# :h => "something else"
# }
@test_hash = {
:a => "something",
:b => "something",
:c => "something",
:d => "something",
:e => "something",
:f => "something",
:g => "something",
}
end
def test_hash_order
assert_equal [ :d, :g, :b, :f, :a, :e, :c], @test_hash.keys
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment