问题描述
我有一个 JSON 结构,我想在其中匹配单个嵌套元素,同时忽略其他数据.JSON 看起来像这样(至少):
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)
我想做的是:
expect(response_json).to include("employee" => { "jobs_count" => 0 })
不幸的是,include
需要精确匹配,除了简单的顶级键检查(至少使用该语法).
Unfortunately, include
requires an exact match for anything but a simple top-level key check (at least with that syntax).
有没有办法在忽略结构的其余部分的同时部分匹配嵌套的哈希?
推荐答案
您可以为这些匹配器使用和嵌套 hash_include
方法.
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)
}))
(或者如果 response_json
是单个对象,将 include
替换为 match
)
(or if response_json
is a single object, replace include
with match
)
这在处理 .with
约束时也有效,例如:
This will also work when dealing with .with
constraints, for example:
expect(object).to receive(:method).with(hash_including(some: 'value'))
这篇关于针对嵌套哈希的 RSpec 部分匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!