期望 xml 响应中的多个元素中至少有一个
Expect at least one of multiple elements in a xml response
我有一个 API 端点,returns 一个 XML 响应。我想测试该响应的一部分。
我有一个 shop
模型,它引用了另一个名为 shop_contact
的 table,它可能为 nil,也可能不是 nil。它包含 3 列,email
、phone
和 fax
我正在用假联系人嘲笑几家商店,我想测试 XML 响应 <shop_contact>
至少包含这些标签(就是这样,<email>
, <phone>
or <fax>
) 且不为空。
我试过了:
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
但是我得到这个错误:
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)
有什么想法吗?
.to_not be_empty
测试数组(或类似数组)是否有元素。所以你可以这样做:
# 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
或者,如果您想坚持使用 ||
s:
expect(shop['shop_contact']['email'] ||
shop['shop_contact']['phone'] ||
shop['shop_contact']['fax']).to be_truthy
我有一个 API 端点,returns 一个 XML 响应。我想测试该响应的一部分。
我有一个 shop
模型,它引用了另一个名为 shop_contact
的 table,它可能为 nil,也可能不是 nil。它包含 3 列,email
、phone
和 fax
我正在用假联系人嘲笑几家商店,我想测试 XML 响应 <shop_contact>
至少包含这些标签(就是这样,<email>
, <phone>
or <fax>
) 且不为空。
我试过了:
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
但是我得到这个错误:
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)
有什么想法吗?
.to_not be_empty
测试数组(或类似数组)是否有元素。所以你可以这样做:
# 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
或者,如果您想坚持使用 ||
s:
expect(shop['shop_contact']['email'] ||
shop['shop_contact']['phone'] ||
shop['shop_contact']['fax']).to be_truthy