ruby – RSpec:如何测试哈希数组中键的存在?
发布时间:2020-12-17 01:34:37 所属栏目:百科 来源:网络整理
导读:我有一节课: 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",# {
我有一节课:
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 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |