Testing hash contents using RSpec

佐手、 提交于 2019-12-03 04:10:00

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

It works for hashes too:

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

Just wanna add to @David's answer. You could nest and use matchers in your include hash. For example:

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

A caveat: a nested include hash must test all keys or the test will fail, e.g.:

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

Syntax has changed for RSpec 3, but include matcher is still the one:

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

See built-in-matchers#include-matcher.

An other easy way to test if the whole content is a Hash is to checkout if the content is the Hash Object itself:

it 'is to be a Hash Object' do
    workbook = {name: 'A', address: 'La'}
    expect(workbook.is_a?(Hash)).to be_truthy
end
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!