使用单引号代替Ruby / Rails中的冒号

问题描述 投票:0回答:1

我正在尝试通过此测试:

 it "returns an object with the correct fields" do 
      expected_response = {"animal_time": @curr_time.strftime("%F %T"), "animals":{}}
      expect(AnimalHaircutSession.latest_for(@animal_haircut)).to eq(expected_response)
  end

当运行测试我得到这个错误:

 expected: {:animal_time=>"2020-02-14 09:48:30", :animals=>{}}
 got: {"animal_time"=>"2020-02-14 16:48:30", "animals"=>{}}

为什么我转换到冒号期望的响应,我该如何设置我的预期的响应使用单引号?

ruby-on-rails ruby
1个回答
3
投票

在Ruby中,冒号用于定义带有键符号的哈希。键将被转换为符号。

{ "foo": "bar" } == { :foo => "bar" } # true
{ "foo": "bar" } != { "foo" => "bar" } # true

如果要定义键不是符号的哈希,请使用哈希火箭(=>)。

it "returns an object with the correct fields" do 
  expected_response = {
    "animal_time" => @curr_time.strftime("%F %T"), 
    "animals" => {}
  }
  expect(AnimalHaircutSession.latest_for(@animal_haircut)).to eq(expected_response)
end

虽然Ruby允许您将哈希火箭和冒号混合在哈希中,但通常认为这不是好形式。

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.