Reputation: 2559
I'm looking for the right way to check for the presence of an attribute in a XML or JSON response. I don't care if the value is nil, empty or any other value, in fact, my response could contain 3 states for this specific attribute:
nil
datetime
So I need some way to unify and simplify all these states (because all are valid in this specific test) and to just ask if the attribute (last_visit_at) is present.
The same I can do to test if it's nil, or not, i.e with JSON:
JSON.parse(response.body).first["last_visit_at"].should_not be_nil
JSON.parse(response.body).first["last_visit_at"].should be_nil
This doesn't work when the value is nil, obviously (nil does not respond to either #exist? or #exists?):
JSON.parse(response.body).first["last_visit_at"].should exist
Is there any way to do this, and could it be valid for both, JSON and XML responses? Thanks.
Upvotes: 0
Views: 4780
Reputation: 19398
try this
JSON.parse(response.body).first.keys.include?("last_visit_at").should be_true
Upvotes: 7