2011-12-05 56 views
42

測試哈希內容我有一個測試,像這樣:使用RSpec的

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 

它,我知道,很冗長。是否有更簡明的方式來陳述我的期望?我查看了文檔,但我無法看到壓縮我的期望的地方。謝謝。

回答

78

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 
) 
+11

謝謝你,大衛。順便說一句巨大的粉絲。真的很喜歡RSpec書。 –

+0

我希望有一個像match_array相應的方法 –

+0

在Fanage David上同上!你的「Rspec書」已經很好了! –

18

只是想添加到@大衛的回答。您可以在您的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 
    } 
}) 
+4

可以通過使用嵌套解決您的警告包括: '''期望({ 「一個」=> { 「B」=> 1, 「C」=> 2 } })以包括(。 {}}包含{{(「b」=> 1 }) })''' – AngelCabo

+0

大多數匹配器都有「動詞」和更長的「名詞」別名,嵌套後者可能會更好: expect {(a「=> {」b「=> 1,」c「=> 2}})。 http://timjwade.com/2016/08/01/testing-json-apis-with-rspec-composable-matchers.html是一個很好的博客文章。 –

2

語法已經改變RSpec的3,但包括匹配器仍一個:

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

請參閱built-in-matchers#include-matcher

0

的其他簡單的方法來測試,如果全部內容是一個Hash是檢出如果內容是哈希對象本身:

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