a是b的json子集,我的意思是
对于数组,b与a的大小相同,但顺序无关紧要
{"one":1}.should be_subset_json({"one":1,"two":2})
[{"one":1}].should_NOT be_subset_json([{"one":1},{"two":2}])
[{"two":2},{"one":1}].should be_subset_json([{"one":1},{"two":2}])
[{"id":1},{"id":2}].should be_subset_json([{"id":2, "name":"b"},{"id":1,"name":"a"}])
答案 0 :(得分:3)
只是实施您的规范似乎有效。
require 'json'
def diff_structure(a, b)
case a
when Array
a.map(&:hash).sort == b.map(&:hash).sort
when Hash
a.all? {|k, v| diff_structure(v, b[k]) }
else
a == b
end
end
RSpec::Matchers.define :be_subset_json do |expected|
match do |actual|
diff_structure JSON.parse(actual), JSON.parse(expected)
end
end
describe "Data structure subsets" do
specify { '{"one":1}'.should be_subset_json('{"one":1,"two":2}') }
specify { '[{"one":1}]'.should_not be_subset_json('[{"one":1},{"two":2}]') }
specify { '[{"two":2},{"one":1}]'.should be_subset_json('[{"one":1},{"two":2}]') }
specify { '{"a":{"one":1}}'.should be_subset_json('{"a":{"one":1,"two":2}}') }
end
# Data structure subsets
# should be subset json "{\"one\":1,\"two\":2}"
# should not be subset json "[{\"one\":1},{\"two\":2}]"
# should be subset json "[{\"one\":1},{\"two\":2}]"
# should be subset json "{\"a\":{\"one\":1,\"two\":2}}"
# Finished in 0.00172 seconds
# 4 examples, 0 failures