tvieira
tvieira

Reputation: 1915

Expect at least one of multiple elements in a xml response

I have an API endpoint, that returns an XML response. There's a part of that response that I want to test.

I have a shop model, that references another table called shop_contact, that may or may not be nil. It contains 3 columns, email, phone and fax

I'm mocking a couple of shops with fake contacts, and I want to test that the XML response <shop_contact>contains AT LEAST of these tags (be it, <email>, <phone>or <fax>) and it's not empty.

I tried:

hash = Hash.from_xml(response.body)
hash["shops"]["shop"].each do |shop|
    expect(shop["shop_contact"]["email"] ||
        shop["shop_contact"]["phone"] ||
        shop["shop_contact"]["fax"]).to_not be_empty
end

but I get this error:

You have a nil object when you didn't expect it! You might have expected an instance of Array. The error occurred while evaluating nil.empty? (NoMethodError)

Any ideas?

Upvotes: 0

Views: 48

Answers (1)

mhutter
mhutter

Reputation: 2916

.to_not be_empty tests whether or not an array (or similar) has elements. So you could do this:

# construct an array
data = [
  shop['shop_contact']['email'],
  shop['shop_contact']['phone'],
  shop['shop_contact']['fax']
].compact # compact removes `nil` elements

expect(data).to_not be_empty

Or, if you want to stick with the ||s:

expect(shop['shop_contact']['email'] ||
       shop['shop_contact']['phone'] ||
       shop['shop_contact']['fax']).to be_truthy

Upvotes: 1

Related Questions