Evan Sitzes
Evan Sitzes

Reputation: 39

How to test value of a single field in a JSON object with RSpec

I am trying to use RSpec with the gem Airborne to test the value of a field in a JSON response of 'people' objects from an API.

Code:

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

So if my test makes an API call with this particular filter (gender), I expect to only pull back people with gender of male. However this code fails, because every 'person' object has many different keys (:name, :age, etc.). I ONLY want to test the gender, but I am unable to get it to pass because expect_json is expecting ALL of the keys in people to be written into the test.

I have combed through Google/Airborne documentation but to no avail: https://github.com/brooklynDev/airborne

Upvotes: 3

Views: 1435

Answers (1)

Wand Maker
Wand Maker

Reputation: 18762

This is place holder answer - to seek more details:

This link produces below JSON from Airborne examples:

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

        ]
    }]
}

Here is an RSpec test (it uses a valid Internet URL, so anyone can try it out)

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

If you run the above test using rspec <filename>.rb, it will given error like below. The error is expected as one of the JSON entry does not have make as Tesla. However, the example demonstrates that Airborne has capability to look at single attribute across all nested JSON objects in a given JSON array.

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

Please update your question with sample JSON and RSpec output to show how your code is similar to above example, as if it was, you should not have faced the issue.

Upvotes: 1

Related Questions