如何检查数组所有元素:当master=true时optin需为true
解决方案
你需要遍历数组里的每一个元素,对每个元素执行检查逻辑,以下是几种可行的实现方式:
方式一:逐个遍历检查
用each循环遍历response["data"]数组,对每个元素判断:如果master为true,就验证optin必须是true:
response["data"].each do |item| if item["master"] == true expect(item["optin"]).to eql true end end
方式二:批量筛选验证
先筛选出所有master为true的元素,再一次性验证它们的optin都为true,代码更简洁:
# 先筛选出master为true的元素集合 master_optins = response["data"].select { |item| item["master"] } # 断言所有筛选出的元素optin都是true expect(master_optins.all? { |item| item["optin"] }).to be true
也可以写成一行紧凑版:
expect(response["data"].select { |i| i["master"] }.all? { |i| i["optin"] }).to be true
方式三:RSpec专属简洁写法
如果用的是RSpec测试框架,还可以用内置的each匹配器结合逻辑判断,直接验证所有元素都符合规则:
expect(response["data"]).to all(satisfy { |item| !item["master"] || item["optin"] })
这里的逻辑是:每个元素要么master不是true,要么master为true时optin也必须是true,完美匹配你的需求。
内容的提问来源于stack exchange,提问作者Jaime Junior
相关产品推荐
相关产品推荐

