RSpec:hash_include不能按预期工作

问题描述 投票:0回答:2

考虑以下json响应:

{
  "data": {
    "someFunction": null
  },
  "errors": [
    {
      "message": "Email was already confirmed, please try signing in",
      "locations": [
        {
          "line": 9,
          "column": 2
        }
      ],
      "path": [
        "someFunction"
      ],
      "extensions": {
        "code": "USER_ERROR"
      }
    }
  ]
}

现在在测试中,我期望以下内容是有效的答案:

expect(json_response[:errors]).to contain_exactly(
  hash_including(
    message: "Email was already confirmed, please try signing in.",
    extensions: { code: 'USER_ERROR' }
  )
)

上面的答复应该是有效的,除了我的测试说不是:

expected collection contained:  [hash_including(:message=>"Email was already confirmed, please try signing in.", :extensions=>{:code=>"USER_ERROR"})]
actual collection contained:    [{:extensions=>{:code=>"USER_ERROR"}, :locations=>[{:column=>9, :line=>2}], :message=>"Email was already confirmed, please try signing in", :path=>["someFunction"]}]
the missing elements were:      [hash_including(:message=>"Email was already confirmed, please try signing in.", :extensions=>{:code=>"USER_ERROR"})]
the extra elements were:        [{:extensions=>{:code=>"USER_ERROR"}, :locations=>[{:column=>9, :line=>2}], :message=>"Email was already confirmed, please try signing in", :path=>["someFunction"]}]

我在这里做错了什么?

ruby-on-rails ruby rspec rspec-rails
2个回答
1
投票

问题是您在测试中做了很多(并且不必嵌套匹配器)

因为contain_exactly匹配器将返回true或错误。

因此,建议不要进行复杂的测试,并在同一测试中尽量避免超过one expectations

  it 'includes data and errors' do
    expect(json_response.keys).to contain_exactly(:data, :errors)
  end

  it 'Email error has message' do
    expect(json_response[:errors][0][:message]).to eq 'Email was already confirmed, please try signing in'
  end

  it 'Email error has code' do
    expect(json_response[:errors][0][:extensions]).to eql(code: 'USER_ERROR')
  end

应该工作


0
投票

[使用Horacio的一项测试,我能够确定自己正在等待一段时间。不使用Rspec的核心功能而不使用它不是我想要的解决方案。但是,这对我自己是一次学习经历,希望遇到此问题的其他人想知道自己做错了什么,他们会发现将contain_exactlyhash_including配对在一起会产生一个简单的错误,可能会导致您的错误输出欺骗您认为实际上您所做的事情确实很错误,您可能犯了一个简单的错误。

此健全性检查:

expect(json_response[:errors][0][:message]).to eq 'Email was already confirmed, please try signing in'

导致我发现我的简单错误:

 expected: "Email was already confirmed, please try signing in."
      got: "Email was already confirmed, please try signing in"
© www.soinside.com 2019 - 2024. All rights reserved.