gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 16:21:50 25 4
gpt4 key购买 nike

我正在尝试将 RSpec 与 gem Airborne 结合使用,以测试来自 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 期望将 people 中的所有键都写入测试中。

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

最佳答案

这是占位符答案 - 以寻求更多详细信息:

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

关于ruby - 如何使用 RSpec 测试 JSON 对象中单个字段的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32148480/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com