ruby-rspec-如何与哈希进行比较?语法错误,意外=>

时间:2019-05-25 21:12:06

标签: ruby rspec

我的哈希似乎没问题,为什么我会收到语法错误?

获取

SyntaxError:
  .../x_and_o_spec.rb:14: syntax error, unexpected =>, expecting '}'
      expect(board).to eq {0 =>"-", 1 =>"-",  2 =>"-",  3 =>"
                               ^
  .../x_and_o_spec.rb:14: syntax error, unexpected ',', expecting keyword_end
   expect(board).to eq {0 =>"-", 1 =>"-",  2 =>"-",  3 =>"-", 
                                ^
  .../x_and_o_spec.rb:14: syntax error, unexpected ',', expecting end-of-input
  oard).to eq {0 =>"-", 1 =>"-",  2 =>"-",  3 =>"-",  4 =>"-",

如果我注释掉了我的期望并只打印了哈希,我得到了:

{0=>"-", 1=>"-", 2=>"-", 3=>"-", 4=>"-", 5=>"-", 6=>"-", 7=>"-", 8=>"-", 9=>"-"}

那我为什么期望给出这些错误消息?

代码

class Grid
  attr_accessor :board
  def initialize
    @board = {}
    (0..9).each do |key|
      @board[key] = "-" 
    end 
  end 
end

测试

it 'Grid has 9 elements, each element is a value of nil, o or X' do
  board = Grid.new.board
  expect(board).to eq {0 =>"-", 1 =>"-",  2 =>"-",  3 =>"-",  4 =>"-",  5 =>"-",  6 =>"-",  7 =>"-",  8 =>"-",  9 =>"-"}
end 

1 个答案:

答案 0 :(得分:3)

如果期望值是散列值,那么程序员对解析器规则的无知(me)。
而不是使用{}

来实现散列/块问题

在其周围加上括号可以解决问题!

 expect(board).to eq    ({0 =>"-", 1 =>"-",  ...  9 =>"-"})
 # added these parens: /\                                /\