运行单元测试时,我期待一个我正在测试的方法返回一个这样的嵌套数组:
[
{:identifier=>"a", :label=>"a label",
:sublist=>[{:identifier=>"sublist z", :label=>"z sublist label"}, {:identifier=>" sublist w", :label=>"sublist w label"}]},
{:identifier=>"b", :label=>"b label",
:sublist=>[{:identifier=>"sublist y", :label=>"y sublist label"}]},
..]
检查返回的数组是否符合预期的最优雅的方法是什么?
如果有任何不同,我正在使用Minitest Spec。
顺便说一句,元素的顺序无关紧要,可能会有所不同。
THX。
答案 0 :(得分:1)
在这种情况下,为custom matcher
写一个minitest
是理想的。
这里是您需要在匹配器中添加的代码。
def match_hash(h1, h2)
matched = false
h1.each do |ele|
h2.each do |ele2|
match_elements?(ele, ele2) ? (matched = true) : next
end
if !matched
return matched
end
end
matched
end
def match_elements?(ele, ele2)
if (ele[:identifier] != ele2[:identifier]) || (ele[:label] != ele2[:label])
return false
end
if ele.has_key?(:sublist) && ele2.has_key?(:sublist)
return match_hash(ele[:sublist], ele2[:sublist])
end
true
end
编写自定义匹配器using this example
然后在测试用例中使用match_hash
来比较两个哈希值。
注意:上面的代码已经过irb测试,效果很好。