开发者

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:

i开发者_如何学Ct "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 (i.e., nil) with:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜