使用RSpec测试哈希内容

时间:2011-12-05 22:37:31

标签: ruby rspec expectations

我有这样的测试:

it "should not indicate backwards jumps if the checker position is not a king" do
    board = Board.new
    game_board = board.create_test_board
    board.add_checker(game_board, :red, 3, 3)
    x_coord = 3
    y_coord = 3
    jump_locations = {}
    jump_locations["upper_left"]  = true 
    jump_locations["upper_right"] = false 
    jump_locations["lower_left"]  = false
    jump_locations["lower_right"] = true
    adjusted_jump_locations = @bs.adjust_jump_locations_if_not_king(game_board, x_coord, y_coord, jump_locations)
    adjusted_jump_locations["upper_left"].should == true 
    adjusted_jump_locations["upper_right"].should == false 
    adjusted_jump_locations["lower_left"].should == false
    adjusted_jump_locations["lower_right"].should == false
  end 

我知道,这很冗长。是否有更简洁的方式来陈述我的期望。我看过文档,但我看不出在哪里压缩我的期望。感谢。

4 个答案:

答案 0 :(得分:86)

http://rubydoc.info/gems/rspec-expectations/RSpec/Matchers:include

它也适用于哈希:

jump_locations.should include(
  "upper_left" => true,
  "upper_right" => false,
  "lower_left" => false,
  "lower_right" => true
)

答案 1 :(得分:25)

只想加入@David的回答。您可以在include哈希中嵌套和使用匹配器。例如:

# Pass
expect({
  "num" => 5, 
  "a" => { 
    "b" => [3, 4, 5] 
  }
}).to include({
  "num" => a_value_between(3, 10), 
  "a" => {
    "b" => be_an(Array)
  }
})

警告:嵌套的include哈希必须测试所有密钥,否则测试将失败,例如:

# Fail
expect({
  "a" => { 
    "b" => 1,
    "c" => 2
  }
}).to include({
  "a" => {
    "b" => 1
  }
})

答案 2 :(得分:3)

RSpec 3的语法已更改,但包括匹配器仍然是:

queue_error*.log

请参阅built-in-matchers#include-matcher

答案 3 :(得分:0)

测试整个内容是否为哈希的另一种简单方法是检查内容是否为哈希对象本身:

format long;
startYCoordinateNorthEast=([50.93952193697642, 6.99745722361763]);