当前位置 : 主页 > 编程语言 > ruby >

ruby – RSpec:如何测试哈希数组中键的存在?

来源:互联网 收集:自由互联 发布时间:2021-06-23
我有一节课: class ApiParser def initialize .. end def api_data # returns an array of hashes like so: # [{ answer: "yes", name: "steve b" age: 22, hometown: "chicago", ... }, # { answer:"unsure", name: "tom z", age: 44, hometown: "bal
我有一节课:

class ApiParser
  def initialize
    ..
  end

  def api_data
    # returns an array of hashes like so:
    # [{ answer: "yes", name: "steve b" age: 22, hometown: "chicago", ... },
    # { answer:"unsure", name: "tom z", age: 44, hometown: "baltimore" , ... },
    # { answer: "no", name: "the brah", age: nil, hometown: "SF", ... }, 
    # { ... }, { ... }, ... ]
  end
end

该方法返回一个哈希数组.数组的长度为50个元素.

每个哈希都具有完全相同的密钥.大约有20把钥匙.

我不确定什么是单元测试这种方法的最佳方法.如何检查该方法确实返回一个数组,每个哈希具有这些键?一些哈希值可能是零,所以我不认为我会测试这些值.

这将有助于:

describe "your test description" do
  let(:hash_keys) { [:one, :two].sort } # and so on

  subject(:array) { some_method_to_fetch_your_array }

  specify do
    expect(array.count).to eq 50

    array.each do |hash|
      # if you want to ensure only required keys exist
      expect(hash.keys).to contain_exactly(*hash_keys)
      # OR if keys are sortable
      # expect(hash.keys.sort).to eq(hash_keys)

      # if you want to ensure that at least the required keys exist
      expect(hash).to include(*hash_keys)
    end
  end
end

该方法存在一个问题:如果测试失败,您将无法确切地找出导致失败的数组索引.添加自定义错误消息将有所帮助.类似于以下内容:

array.each_with_index do |hash, i|
  expect(hash.keys).to contain_exactly(*hash_keys), "Failed at index #{i}"
end
网友评论