Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 385
raidfive Avatar asked Jan 30 '11 23:01

raidfive


Video Answer


1 Answers

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 (i.e., nil) with:

t['tags'].to_a.detect { |e| e['name'] == 'authentication' }
like image 94
DigitalRoss Avatar answered Sep 21 '22 17:09

DigitalRoss