在我的規范中,我有以下的回應結構
something:/span> { foo: [{bar: 'baz'}, {one: 'two'}] }
我試著進行比較,但是foo-array里面的順序是隨機的。 我找到了這篇文章。 鏈接,其中有以下代碼:
當你有一個陣列,但無法確定元素的順序時,請使用a_collection_containing_exactly
。expected = { "data"/span> => a_collection_containing_exactly( a_hash_including("id" => "1") 。 a_hash_including("id"/span> => "2") ) } expect(response.parsed_body).to include(expected)
但是這對我來說不起作用,因為比較時看到匹配器a_collection_containing_exactly作為哈希的一部分
{"base_matcher"=>{" expected"=>[{bar:
我錯過了什么?有什么更好的解決方案嗎?
編輯。 為了說明問題,這里有一個最小的可重復的例子
expected_value = { something:/span> { foo: [{ bar: 'baz' }, { one: 'two' }] ! }}
expect(response.parsed_body).to eq(expected_value)
uj5u.com熱心網友回復:
我認為RSpec的match_array匹配器是你需要的:
array_of_hashes = [{bar: "baz"},{one: "wo"}]
expect(response.parsed_body[:foo]).to match_array(array_of_hashes)
如果你的頂層哈希有很多鍵,你可以寫一個自定義匹配器:
# in spec/matchers/match_sort_indifferent.rb:
require 'rspec/expectations'
RSpec::Matchers.define : match_sort_indifferent do |expected|
匹配 do |actual|
expected.key.each do | key|
expect(actual[key]).to match_array expected[key]
結束
expect(expected.key.length).to eq actual.key.length
end
end end
# in spec/models/test_spec.rb
require 'rails_helper' >。
require 'matchers/match_sort_indifferent'
結果 = {foo: [{bar: "baz"},{qux: "dak"}] }
描述 {
它 {
expect(result). to match_sort_indifferent({foo: [{qux: "dak"},{bar: " baz"}]})
expect(result). not_to match_sort_indifferent({foo: [{qux: "sum"},{bar: " baz"}]})
}
}
uj5u.com熱心網友回復:
謝謝你的回答。我在Rspec-json-expectations gem和UnorderedArray的幫助下解決了這個問題
。所以我的解決方案是這樣的:
expected_value = { something: { foo。 UnorderedArray({ bar: 'baz' }, { one: 'two' }) }}
和匹配器
expect(response.parsed_body).to include_json expected_value
缺點是,它只檢查是否存在預期的值,而不捕捉額外的值。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/307614.html
標籤:
