Skip to content

Instantly share code, notes, and snippets.

@RyanSnodgrass
Created March 30, 2022 13:21
Show Gist options
  • Save RyanSnodgrass/80f2fefa3c1648108950e34e018be74e to your computer and use it in GitHub Desktop.
Save RyanSnodgrass/80f2fefa3c1648108950e34e018be74e to your computer and use it in GitHub Desktop.
Assertion for RSpec that checks if a hash or json object is within another json object
RSpec::Matchers.define :include_json do |expected_json|
match do |actual_json|
expect(hashify(actual_json)).to include(hashify(expected_json))
end
def hashify(object)
return object.stringify_keys if object.class == Hash
JSON.parse(object)
end
end
describe ':include_json' do
context 'subject as json' do
subject { { 'hello' => 'world', 'foo' => 'bar' }.to_json }
context 'expectation as hash' do
it { should include_json({ foo: 'bar', hello: 'world' }) }
it { should include_json( { hello: 'world' }) }
it { should_not include_json( { hello: 'world', bar: 'baz' }) }
it { should_not include_json( { bar: 'baz' }) }
end
context 'expectation as json' do
it { should include_json( { hello: 'world' }.to_json ) }
it { should include_json( { 'foo' => 'bar', 'hello' => 'world' }.to_json ) }
it { should_not include_json( { 'XXXX' => 'XXX'}.to_json ) }
end
end
context 'subject as hash' do
subject { { fizz: [1, 2, 3], buzz: true } }
context 'expectation as hash' do
it { should include_json( { fizz: [1, 2, 3], buzz: true } ) }
it { should include_json( { buzz: true }) }
it { should_not include_json( { hello: 'world', buzz: true }) }
it { should_not include_json( { buzz: false }) }
end
context 'expectation as json' do
it { should include_json( { fizz: [1,2,3] }.to_json ) }
it { should_not include_json( { 'XXXX' => 'XXX'}.to_json ) }
it { should_not include_json( { fizz: [4,5,6] }.to_json ) }
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment