Home > Back-end >  How to check multiples itens of an array?
How to check multiples itens of an array?

Time:07-29

everyone, I'm trying to check an information from every item of an array but I don't know how to do this for all the 4 items, first that's the standard response:

data: [{"optinId": "3fa85f64-5717-4562-b3fc-2c963f66afa6",  "name": "string",  "description": string",  "alertMessage": "string",  "master": true,  "optin": true}]

this example has only 1 item but the true I have has 4, what I have to do is "expect when MASTER=true then OPTIN=true", I started with a simple IF:

 if (response["data"][0]["master"]=true)  
 expect(@response["data"][0]["optin"]).to eql true
 end

that solution isn't enough for me because I want to check all 4 items of the array, can someone please help me with a solution?

CodePudding user response:

You can find the item you want with .find method and assert the fields you want.

item = response[:data].find { |item| item[:master] }
expect(item&.dig(:optin)).to eql(true)

This code will assert there must be a item with master true and optin true

CodePudding user response:

try iterating through items in the array, using a for loop or for each

example:

arr = [{"optinId": "3fa85f64-5717-4562-b3fc-2c963f66afa6",  "name": "string",  "description": string",  "alertMessage": "string",  "master": true,  "optin": true}]

arr.each do |item|
  /** your code **/
end

CodePudding user response:

item = @response["data"].find { |item| item["master"]==true }
expect(item["optin"]).to eql true

that solved my problem, thanks to Mehmet Adil Istikbal and everyone else that contribute

  • Related