bra*_*bag 0 ruby testing rspec ruby-hash
我需要验证哈希的内容,我惊讶地发现 RSpeccontain_exactly只适用于数组。理想的期望是:
expect(type.values.values).to contain_exactly(
ONE: an_object_having_attributes(value: 'uno'),
TWO: an_object_having_attributes(value: 'dos')
)
Run Code Online (Sandbox Code Playgroud)
基本要求是contain_exactly要求数组仅包含这些元素,并且哈希等效项必须仅包含指定的确切键/值对。
有很多解决方法都可以:
include(key: value),但这允许其他键,我需要完全匹配。expect(hash.keys).to contain_exactly(...)但这并不能验证键是否专门链接到值。contain_exactly(将哈希读取为元组[key, value])并基于子数组进行匹配,例如contain_exactly(a_collection_containing_exactly('ONE', an_object_having_attributes(value: 'uno')), ...)aggregate_failures。等等,但我最好奇是否有内置的 RSpec 方法可以做到这一点。
你可以match像这样使用匹配器
require "ostruct"
describe do
let(:hash) do
{
one: OpenStruct.new(x: 1),
two: OpenStruct.new(y: 2)
}
end
it "matches hashes" do
expect(hash).to match(
two: an_object_having_attributes(y: 2),
one: an_object_having_attributes(x: 1)
)
end
it "requires the actual to have all elements of the expected" do
expect(a: 1, b: 2).not_to match(b: 2)
end
it "requires the expected to have all elements of the actual" do
expect(a: 1).not_to match(a: 1, b: 2)
end
end
Run Code Online (Sandbox Code Playgroud)
如果此哈希值之一具有额外的密钥 - 测试将失败
| 归档时间: |
|
| 查看次数: |
2505 次 |
| 最近记录: |