【问题标题】:RSpec test of hash failing due to symbol, not Rails由于符号而不是 Rails 导致哈希失败的 RSpec 测试
【发布时间】:2015-06-28 13:44:23
【问题描述】:

我没有使用 Rails,只是使用 Ruby 和 RSpec 并试图通过哈希对测试。正确的结果在 IRB 上通过,但测试始终包含使测试失败的分号。

这是 RSpec 测试:

 describe Menu do
      let(:menu) { described_class.new }
      let(:book) { double :book, name: 'Clockwise to Titan', price: 6 }

      it 'can add a dish to the menu list' do
        menu.add(book)
        expect(menu.list).to eq({'Clockwise to Titan': 6})
      end
    end

这是失败:

Failures:

1) Menu can add a dish to the menu list
   Failure/Error: expect(menu.list).to eq({'Clockwise to Titan': 6})

   expected: {:"Clockwise to Titan"=>6}
        got: {"Clockwise to Titan"=>6}

   (compared using ==)

   Diff:
   @@ -1,2 +1,2 @@
   -:"Clockwise to Titan" => 6,
   +"Clockwise to Titan" => 6,

 # ./spec/menu_spec.rb:9:in `block (2 levels) in <top (required)>'

我在 Stack Overflow 上找到了许多关于 HashWithIndifferentAccess 解决的类似问题的参考资料,但我没有使用 Rails。此外,有时建议的 stringify_keys 方法也不起作用。

【问题讨论】:

    标签: ruby hash rspec symbols


    【解决方案1】:

    从代码看起来,你应该改变:

    expect(menu.list).to eq({'Clockwise to Titan': 6})
    

    expect(menu.list).to eq({'Clockwise to Titan' => 6})
    

    使规范通过。

    您的问题是,您定义了一个hash,其中的键不是String,而是Symbol

    考虑一下:

    {'Clockwise to Titan': 6} == {:'Clockwise to Titan' => 6}
    

    但是

    {'Clockwise to Titan': 6} != {'Clockwise to Titan' => 6}
    

    希望这会有所帮助!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-02-05
      • 2013-09-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多