简体   繁体   中英

Efficiently check that a JSON response contains a specific element within an array

Given the JSON response:

{
  "tags": [
    {
      "id": 81499,
      "name": "sign-in"
    },
    {
      "id": 81500,
      "name": "user"
    },
    {
      "id": 81501,
      "name": "authentication"
    }
  ]
}

Using RSpec 2, I want to verify that this response contains the tag with the name authentication. Being a fairly new to Ruby, I figured there is a more efficient way than iterating the array and checking each value of name using include? or map/collect. I could simply user a regex to check for /authentication/i but that doesn't seem like the best approach either.

This is my spec so far:

it "allows filtering" do
  response = @client.story(15404)

  #response.tags.
end

So, if

t = JSON.parse '{ ... }'

Then this expression will either return nil , which is false, or it will return the thing it detected, which has a boolean evaluation of true.

t['tags'].detect { |e| e['name'] == 'authentication' }

This will raise NoMethodError if there is no tags key. I think that's handled just fine in a test, but you can arrange for that case to also show up as false (ie, nil) with:

t['tags'].to_a.detect { |e| e['name'] == 'authentication' }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM