2

I have a controller action where i am assigning a hash to an instance variable. In my rspec test file, i am using assigns to test it the instance variable is assigned to the value i expect. For some reason, assigns gives me a hash with string keys. If i print the instance variable in the controller, i has symbol keys

Please find the code below. It is simplified.

class TestController < ApplicationController
  def test
    @test_object = {:id => 1, :value => 2, :name => "name"}
  end
end

My test file:

describe TestController do
  it "should assign test_object" do
    get :test
    assigns(:test_object).should == {:id => 1, :value => 2, :name => "name"}
  end
end

The above test fails with the error message

expected: {:id=>1, :value=>2, :name=>"name"}
     got: {"id"=>1, "value"=>2, "name"=>"name"}

Please help me understand why it is doing that.

usha
  • 28,973
  • 5
  • 72
  • 93
  • 1
    possible duplicate of [Unwanted symbol to string conversion of hash key](http://stackoverflow.com/questions/4348195/unwanted-symbol-to-string-conversion-of-hash-key) – Peter Alfvin Jun 27 '13 at 20:58

1 Answers1

4

RSpec borrows assigns from the regular Rails test/unit helpers and it's using with_indifferent_access to return the requested instance variable as in assigns(:my_var).

Hash#with_indifferent_access returns a key-stringified version of the hash (a deep copy), which has the side effect of stringfiying the keys of instance variables that are hashes.

If you try to match the entire hash, it will fail, but it works if you are checking the values of specific keys, whether they're a symbol or a string.

Maybe an example will help clarify:

{:a => {:b => "bravo"}}.with_indifferent_access => {"a"=>{"b"=>"bravo"}} 
{:a => {:b => "bravo"}}.with_indifferent_access[:a][:b] => "bravo"
boulder
  • 3,256
  • 15
  • 21