【问题标题】:How to test value of a single field in a JSON object with RSpec如何使用 RSpec 测试 JSON 对象中单个字段的值
【发布时间】:2015-11-15 21:07:36
【问题描述】:

我正在尝试使用带有 gem Airborne 的 RSpec 来测试来自 API 的“人”对象的 JSON 响应中的字段值。

代码:

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

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

我已经梳理了 Google/Airborne 文档,但无济于事: https://github.com/brooklynDev/airborne

【问题讨论】:

  • 文档说你做得对。您是否仔细检查过响应是否正确? json 输出本身是什么?
  • 所以每个 person 对象的 json 响应是: Person: { gender: "MALE", name: "John", age: 21 } (实际上还有很多很多键,但这只是一个例子)
  • 已经仔细检查了响应。它列出了 JSON 中的所有键,并说它与预期不匹配,然后在“差异:”部分列出了我未包含在测试中的键
  • 你得到的是一个人对象数组people : [{person},{person}]还是很多人的对象? people: {{person},{person}} ?
  • 人员对象数组 people people : [{person},{person}]

标签: ruby json rspec airborne


【解决方案1】:

这是占位符答案 - 寻求更多细节:

这个link 从 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 条目之一没有 makeTesla。但是,该示例表明 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 输出更新您的问题,以显示您的代码与上述示例的相似之处,就好像您不应该遇到问题一样。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-03-07
    • 2017-12-09
    • 1970-01-01
    • 2016-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多