diff --git a/lib/json_spec/exclusion.rb b/lib/json_spec/exclusion.rb index cde4516..098ebf0 100644 --- a/lib/json_spec/exclusion.rb +++ b/lib/json_spec/exclusion.rb @@ -16,11 +16,19 @@ def exclude_keys(ruby) end def exclude_key?(key) - excluded_keys.include?(key) + if only_keys.empty? + excluded_keys.include?(key) + else + !only_keys.include?(key) + end end def excluded_keys @excluded_keys ||= Set.new(JsonSpec.excluded_keys) end + + def only_keys + @only_keys ||= Set.new + end end end diff --git a/lib/json_spec/matchers/be_json_eql.rb b/lib/json_spec/matchers/be_json_eql.rb index d1c0b1e..8e91a01 100644 --- a/lib/json_spec/matchers/be_json_eql.rb +++ b/lib/json_spec/matchers/be_json_eql.rb @@ -42,6 +42,11 @@ def including(*keys) self end + def only(*keys) + only_keys.merge(keys.map(&:to_s)) + self + end + def failure_message_for_should message_with_path("Expected equivalent JSON") end diff --git a/lib/json_spec/matchers/include_json.rb b/lib/json_spec/matchers/include_json.rb index a341f2e..716920c 100644 --- a/lib/json_spec/matchers/include_json.rb +++ b/lib/json_spec/matchers/include_json.rb @@ -42,6 +42,11 @@ def including(*keys) self end + def only(*keys) + only_keys.merge(keys.map(&:to_s)) + self + end + def failure_message_for_should message_with_path("Expected included JSON") end diff --git a/spec/json_spec/matchers/be_json_eql_spec.rb b/spec/json_spec/matchers/be_json_eql_spec.rb index 7690e60..aa0c619 100644 --- a/spec/json_spec/matchers/be_json_eql_spec.rb +++ b/spec/json_spec/matchers/be_json_eql_spec.rb @@ -86,6 +86,11 @@ %({"id":1,"json":"spec"}).should_not be_json_eql(%({"id":2,"json":"different"})).including(:id, :json) end + it 'matching only the specified keys' do + JsonSpec.excluded_keys = [] + %({"id":1,"json":"spec"}).should be_json_eql(%({"id":1})).only(:id) + end + it "provides a description message" do matcher = be_json_eql(%({"id":2,"json":"spec"})) matcher.matches?(%({"id":1,"json":"spec"})) diff --git a/spec/json_spec/matchers/include_json_spec.rb b/spec/json_spec/matchers/include_json_spec.rb index 528ae28..5709cbc 100644 --- a/spec/json_spec/matchers/include_json_spec.rb +++ b/spec/json_spec/matchers/include_json_spec.rb @@ -59,6 +59,10 @@ %([{"id":1,"two":3}]).should include_json(%({"two":3})) end + it 'matching only the specified keys' do + %([{"id":1,"json":"spec"}]).should include_json(%({"id":1})).only(:id) + end + it "provides a description message" do matcher = include_json(%({"json":"spec"})) matcher.matches?(%({"id":1,"json":"spec"}))