允许 eq 比较中的数组内容是 rspec 测试中的任何内容

Allow contents of array in eq comparison to be anything in rspec test

我有一个使用 Ruby 的 GraphQL API(在 Rails 上)并且在编写请求测试时遇到过这样一种情况,即为了保持高可读性应该接受一个数组来拥有任何eq 比较中的内容。

像这样:

         expect(json_response).to eq({
            data: {
              Post: {
                PostId: nil,
                wasUpdated: false,
                errors[<Any error acceptet here>]
              }
            }
          })

我试过: errors[*] ... 没用。

让我带您了解一下。这是一个通用测试,用于查看 PostId: nil 和 wasUpdated: false 以及发生某些错误时返回的错误数组。由于这是一般的失败测试,​​因此没有必要指定返回的具体错误。

因此我的问题;我该如何编写以允许上述所有预期但在错误数组中发生任何事情?

您可以使用 RSpec 合成来帮助解决这个问题 Docs

在这种情况下,您的测试将如下所示:

expect(json_response).to match({
        data: {
          Post: {
            PostId: nil,
            wasUpdated: false,
            errors: an_instance_of(Array)
          }
        }
      }) 

Working Example