使用RSpec测试哈希内容

ste*_*her 54 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 
Run Code Online (Sandbox Code Playgroud)

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

Dav*_*sky 89

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
)
Run Code Online (Sandbox Code Playgroud)

  • 谢谢,大卫.BTW巨大的粉丝.真的很喜欢RSpec的书. (12认同)
  • 我希望有一个像match_array这样的对应方法 (2认同)

Ben*_*eah 31

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

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

需要注意的是:嵌套include哈希必须测试所有键,否则测试将失败,例如:

# Fail
expect({
  "a" => { 
    "b" => 1,
    "c" => 2
  }
}).to include({
  "a" => {
    "b" => 1
  }
})
Run Code Online (Sandbox Code Playgroud)

  • 你可以通过使用嵌套的包含来解决你的警告:```expect({"a"=> {"b"=> 1,"c"=> 2}}).包括({"a"=> include( {"b"=> 1})})``` (6认同)
  • 大多数匹配器都有“动词”和更长的“名词”别名,后者在嵌套时可能读得更好:`expect({ "a" => { "b" => 1, "c" => 2 } }).to include({ "a" => a_hash_include({ "b" => 1 }) })`。http://timjwade.com/2016/08/01/testing-json-apis-with-rspec-composable-matchers.html 是一篇很好的博客文章。 (2认同)

Mar*_*jaš 6

RSpec 3 的语法已经改变,但包含匹配器仍然是一个:

expect(jump_locations).to include(
  "upper_left" => true,
  "upper_right" => false,
  "lower_left" => false,
  "lower_right" => true
)
Run Code Online (Sandbox Code Playgroud)

请参阅内置匹配器#include-matcher


Kir*_*eas 5

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

it 'is to be a Hash Object' do
    workbook = {name: 'A', address: 'La'}
    expect(workbook.is_a?(Hash)).to be_truthy
end
Run Code Online (Sandbox Code Playgroud)

对于上面的问题我们可以检查如下:

it 'is to be a Hash Object' do
    workbook = {name: 'A', address: 'La'}
    expect(workbook.is_a?(Hash)).to be_truthy
end
Run Code Online (Sandbox Code Playgroud)