2

我有一个控制器操作,我将哈希分配给实例变量。在我的 rspec 测试文件中,我使用 assigns 来测试它,实例变量被分配给我期望的值。出于某种原因,assigns 给了我一个带有字符串键的散列。如果我在控制器中打印实例变量,我有符号键

请在下面找到代码。它被简化了。

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

我的测试文件:

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

上述测试失败并显示错误消息

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

请帮助我理解它为什么这样做。

4

1 回答 1

4

RSpec 从常规的 Rails 测试/单元助手中借用赋值,它使用 with_indiffer_access 返回请求的实例变量,如assigns(:my_var).

Hash#with_indifferent_access返回哈希的键字符串化版本(深层副本),其副作用是对作为哈希的实例变量的键进行字符串化。

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"
于 2013-06-27T21:08:56.743 回答