RSpec partial match against a nested hash

心不动则不痛 提交于 2020-05-09 20:34:39

问题


I've got a JSON structure that I'd like to match a single nested element in, while ignoring other data. The JSON looks like this (minimally):

{
  "employee": {
    "id": 1,
    "jobs_count": 0
  },
  "messages": [ "something" ]
}

Here's what I'm using right now:

response_json = JSON.parse(response.body)
expect(response_json).to include("employee")
expect(response_json["employee"]).to include("jobs_count" => 0)

What I'd like to do is something like:

expect(response_json).to include("employee" => { "jobs_count" => 0 })

Unfortunately, include requires an exact match for anything but a simple top-level key check (at least with that syntax).

Is there any way to partially match a nested hash while ignoring the rest of the structure?


回答1:


You are able to use and nest the hash_including method for these matchers.

Using your example, you can rewrite your test code to look like:

expect(response_json).to include(hash_including({
  employee: hash_including(jobs_count: 0)
}))

(or if response_json is a single object, replace include with match)

This will also work when dealing with .with constraints, for example:

expect(object).to receive(:method).with(hash_including(some: 'value'))



回答2:


With rspec 3.6.0, this works for me:

expect(subject).to match(a_hash_including(key: value))


来源:https://stackoverflow.com/questions/40325820/rspec-partial-match-against-a-nested-hash

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!