由于符号而不是Rails,散列失败的RSpec测试(RSpec test of hash failing due to symbol, not Rails)

我没有使用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方法不起作用。

I am not using Rails, just Ruby & RSpec and trying to pass a hash pair test. The right result is coming through on IRB, but the test keeps including a semi-colon that makes the test fail.

Here is the RSpec test:

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

Here is the failure:

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)>'

I have found a number of references on Stack Overflow to a similar problem solved by HashWithIndifferentAccess, but I am not using Rails. Also, the sometimes-suggested stringify_keys method is not working.

最满意答案

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

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}

希望这可以帮助!

From the code it looks like, you should change:

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

to

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

to make the spec pass.

The problem in your case is, you defined a hash where a key is not a String, but a Symbol.

Consider this:

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

but

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

Hope this helps!

更多推荐