测试嵌套列表是否符合预期的最佳方法是什么?

时间:2014-03-04 15:45:28

标签: ruby-on-rails testing ruby-on-rails-4

运行单元测试时,我期待一个我正在测试的方法返回一个这样的嵌套数组:

[
{: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。

1 个答案:

答案 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测试,效果很好。