3

a是b的json子集,我的意思是

  • 对于 object,b 具有 a 中的所有键值对。
  • 对于数组,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"}])
    
4

1 回答 1

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
于 2013-08-28T20:54:26.740 回答