使用RSpectesting哈希内容
我有这样的testing:
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
我知道这是详细的。 有一个更简洁的方式来陈述我的期望。 我已经看过文档,但是我看不到在哪里压缩我的期望。 谢谢。
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 )
只是想添加@大卫的答案。 你可以在你的include
哈希中嵌套和使用匹配器。 例如:
# Pass expect({ "num" => 5, "a" => { "b" => [3, 4, 5] } }).to include({ "num" => a_value_between(3, 10), "a" => { "b" => be_an(Array) } })
警告:嵌套include
哈希必须testing所有键或testing将失败,例如:
# Fail expect({ "a" => { "b" => 1, "c" => 2 } }).to include({ "a" => { "b" => 1 } })
RSpec 3的语法已经改变了,但是匹配器仍然是一个:
expect(jump_locations).to include( "upper_left" => true, "upper_right" => false, "lower_left" => false, "lower_right" => true )
参见内置匹配器#include-matcher 。
testing整个内容是否为散列的另一个简单方法是检查内容是否为散列对象本身:
it 'is to be a Hash Object' do workbook = {name: 'A', address: 'La'} expect(workbook.is_a?(Hash)).to be_truthy end