Created
April 11, 2018 00:11
-
-
Save pje/5fe7ecefb0318074f4495f071b80d28e to your computer and use it in GitHub Desktop.
Mocha matcher to recursively match nested data structures
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'mocha/parameter_matchers/base' | |
module Mocha | |
module ParameterMatchers | |
# @example | |
# partial = { | |
# a: [ 1, 2 ], | |
# b: { | |
# hello: { | |
# world: [ 'foo' ] | |
# } | |
# } | |
# } | |
# | |
# full = { | |
# a: [ 1, 2, 3 ], | |
# b: { | |
# hello: { | |
# world: [ 'foo', 'bar' ] | |
# } | |
# }, | |
# c: 'baz' | |
# } | |
# | |
# object = mock() | |
# object.expects(:method_1).with(partial_object(partial)) | |
# object.method_1(full) | |
# # no error raised | |
def partial_object(o) | |
PartialObject.new(o) | |
end | |
class PartialObject < ::Mocha::ParameterMatchers::Base | |
def initialize(partial) | |
@partial = partial | |
end | |
def matches?(available_parameters) | |
_matches?(@partial, available_parameters.shift) | |
end | |
def _matches?(partial, other) | |
case partial | |
when ::Mocha::ParameterMatchers::Base | |
partial.matches?(other) | |
when Hash | |
partial.all? { |k, v| other.has_key?(k) && _matches?(v, other[k]) } | |
when Enumerable | |
partial.zip(other).all? { |a, b| _matches?(a, b) } | |
else | |
partial == other | |
end | |
end | |
def mocha_inspect | |
"partial_object(#{@partial.mocha_inspect})" | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment