如何使用RSpec测试JSON对象中单个字段的值



我正在尝试使用RSpec与gem Airborne来测试来自API的'people'对象的JSON响应中的字段值。

代码:

  it 'GET list of people objects where gender = male' do
    get "/people?gender=male"
    expect_json('people.*', {gender: 'MALE'})
  end

因此,如果我的测试使用这个特定的过滤器(性别)进行API调用,我希望只拉回性别为男性的人。然而,这段代码失败了,因为每个"person"对象都有许多不同的键(:name,:age等)。我只想测试性别,但我无法让它通过,因为expect_json期望所有的键在人被写入测试。

我已经梳理了谷歌/机载文档,但无济于事:https://github.com/brooklynDev/airborne

这是占位符答案-查看更多细节:

这个链接从Airborne示例中生成以下JSON:

{
    "cars": [{
        "make": "Tesla",
        "model": "Model S",
        "owners": [
            {"name": "Bart Simpson"}
        ]
    }, {
        "make": "Lamborghini",
        "model": "Aventador",
        "owners": [
            {"name": "Peter Griffin"}
        ]
    }]
}

这是一个RSpec测试(它使用一个有效的Internet URL,所以任何人都可以尝试一下)

require 'airborne'
describe 'sample spec' do
  it 'should validate car make' do
    get 'https://raw.githubusercontent.com/brooklynDev/airborne/master/spec/test_responses/array_with_nested.json'
    expect_json('cars.*', make: 'Tesla')
  end
end

如果您使用rspec <filename>.rb运行上述测试,它将给出如下错误:该错误是预期的,因为其中一个JSON条目没有将make作为Tesla。然而,该示例演示了Airborne能够在给定JSON数组中的所有嵌套JSON对象中查看单个属性。

E:elixir>rspec fun.rb
F
Failures:
  1) sample spec should validate car make
     Failure/Error: expect_json('cars.*', make: 'Tesla')
       expected: "Tesla"
            got: "Lamborghini"
       (compared using ==)
     # ./fun.rb:6:in `block (2 levels) in <top (required)>'
Finished in 3.98 seconds (files took 0.68346 seconds to load)
1 example, 1 failure
Failed examples:
rspec ./fun.rb:4 # sample spec should validate car make

请使用示例JSON和RSpec输出更新您的问题,以显示您的代码如何与上面的示例相似,就好像它是,您不应该面对这个问题。

最新更新