编写rspec测试以检查返回哈希表的函数

时间:2017-02-14 05:02:03

标签: ruby-on-rails rspec

尝试编写一个RSpec测试,检查函数location_counts(piece),该函数返回一个散列表,其中包含一些键和值。

 describe "location_counts(piece)" do
   it "should return a hash table with a key of locations and value of times visited" do
     game = FactoryGirl.create(:game)
     black_queen = FactoryGirl.create(:queen, game_id: game.id, row: 8, column: 4, is_black: true)

     black_queen.move_to(4,4)
     black_queen.move_to(1,1)
     black_queen.move_to(4,4)

   expect(game.location_counts(black_queen)).to be {"4, 4"=>2, "1, 1"=>1}
  end
end

通过此测试,我收到语法错误。 看起来像是:

/usr/local/rvm/gems/ruby-2.3.0/gems/rspec-core-3.5.4/lib/rspec/core/configuration.rb:1435:in `load': /home/ubuntu/workspace/chess-app/spec/models/game_spec.rb:101: syntax error, unexpected =>, expecting '}' (SyntaxError)
...s(black_queen)).to be {"4, 4"=>2, "1, 1"=>1} 
...                               ^
/home/ubuntu/workspace/chess-app/spec/models/game_spec.rb:101: syntax error, unexpected =>, expecting '}'
...en)).to be {"4, 4"=>2, "1, 1"=>1} 
...                               ^

1 个答案:

答案 0 :(得分:0)

问题似乎是ruby正在解释你预期的哈希:

expect(game.location_counts(black_queen)).to be {"4, 4"=>2, "1, 1"=>1}

作为传递给be方法的块,而不是作为参数。请尝试以下方法:

expect(game.location_counts(black_queen)).to eq({"4, 4"=>2, "1, 1"=>1})

甚至删除花括号,因为哈希是传递给be方法的最后一个参数:

expect(game.location_counts(black_queen)).to eq("4, 4"=>2, "1, 1"=>1)

编辑:请注意使用eq代替be