我有一节课:
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
每个哈希都具有完全相同的密钥.大约有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