针对嵌套哈希的 RSpec 部分匹配 [英] RSpec partial match against a nested hash

查看:33
本文介绍了针对嵌套哈希的 RSpec 部分匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 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 部分匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆