Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unwanted symbol to string conversion of hash key

When I assign in my controller

@my_hash = { :my_key => :my_value }

and test that controller by doing

get 'index'
assigns(:my_hash).should == { :my_key => :my_value }

then I get the following error message:

expected: {:my_key=>:my_value},
got: {"my_key"=>:my_value} (using ==)

Why does this automatic symbol to string conversion happen? Why does it affect the key of the hash?

like image 552
Zardoz Avatar asked Dec 03 '10 17:12

Zardoz


2 Answers

You might try calling "stringify_keys":

assigns(:my_hash).should == { :my_key => :my_value }.stringify_keys
like image 200
coder_tim Avatar answered Nov 05 '22 01:11

coder_tim


It may end up as a HashWithIndifferentAccess if Rails somehow gets ahold of it, and that uses string keys internally. You might want to verify the class is the same:

assert_equal Hash, assigns(:my_hash).class

Parameters are always processed as the indifferent access kind of hash so you can retrieve using either string or symbol. If you're assigning this to your params hash on the get or post call, or you might be getting converted.

Another thing you can do is freeze it and see if anyone attempts to modify it because that should throw an exception:

@my_hash = { :my_key => :my_value }.freeze
like image 8
tadman Avatar answered Nov 05 '22 00:11

tadman