Effectively check that the JSON response contains a specific element inside the 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 answer contains a tag with name authentication. Being fairly new to Ruby, I decided that there was a more efficient way than repeating an array and checking each name value with include? or collect cards. I could just use regex to validate / authenticate / i, but that doesn't seem like the best approach.

This is my specification:

 it "allows filtering" do response = @client.story(15404) #response.tags. end 
+4
source share
1 answer

So if

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

Then this expression will either return nil , which is false, or it will return a discovered thing that has a logical evaluation of true.

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

This will raise a NoMethodError if there is no tags key. I think that everything was fine in the test mode, but you can also arrange for this to display false (i.e. Nil) with:

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

Source: https://habr.com/ru/post/1337704/


All Articles