我正在编写一个测试用例,以确保所有关键字段(如total_interactions,shares,comments和like)都是哈希中存在的键。
不确定我为什么会遇到这个例外:
NoMethodError: undefined method `has_key?' for ["total_interactions", {"value"=>1170.0}]:Array
以下是我签到的哈希:
{13=>{"total_interactions"=>{"value"=>1170.0}, "shares"=>{"value"=>850.0}, "comments"=>{"value"=>0.0}, "likes"=>{"value"=>320.0}}, 17=>{"total_interactions"=>{"value"=>701.0}, "shares"=>{"value"=>300.0}, "comments"=>{"value"=>0.0}, "likes"=>{"value"=>401.0}}, 12=>{"total_interactions"=>{"value"=>203.66666666666666}, "shares"=>{"value"=>100.66666666666667}, "comments"=>{"value"=>0.0}, "likes"=>{"value"=>103.0}}, 22=>{"total_interactions"=>{"value"=>11.0}, "shares"=>{"value"=>2.0}, "comments"=>{"value"=>0.0}, "likes"=>{"value"=>9.0}}}
这是应该执行此操作的方法。
def test_aggs_response_populated(aggs_results)
aggs_results.each do |k,v|
if(v.class == Hash)
contains_interactions = false
contains_shares = false
contains_comments = false
contains_likes = false
v.each do |hash_item|
contains_interactions = hash_item.has_key?("total_interactions")
contains_shares = hash_item.has_key?("shares")
contains_comments = hash_item.has_key?("comments")
contains_likes = hash_item.has_key?("likes")
end
assert_equal(true, contains_interactions)
assert_equal(true, contains_shares)
assert_equal(true, contains_comments)
assert_equal(true, contains_likes)
end
end
end
答案 0 :(得分:0)
你循环遍历哈希两次。你不想在键/值对上使用has_key。
你应该改变
v.each do |hash_item|
contains_interactions = hash_item.has_key?("total_interactions")
contains_shares = hash_item.has_key?("shares")
contains_comments = hash_item.has_key?("comments")
contains_likes = hash_item.has_key?("likes")
end
到
contains_interactions = v.has_key?("total_interactions")
contains_shares = v.has_key?("shares")
contains_comments = v.has_key?("comments")
contains_likes = v.has_key?("likes")