Skip to content

Instantly share code, notes, and snippets.

@jejacks0n
Last active December 21, 2015 23:49
Show Gist options
  • Save jejacks0n/6384919 to your computer and use it in GitHub Desktop.
Save jejacks0n/6384919 to your computer and use it in GitHub Desktop.
module JsonSpec::Matchers
def look_like(json = nil)
JsonSpec::Matchers::LookLike.new(json)
end
class LookLike < BeJsonEql
def matches?(actual_json)
raise "Expected equivalent JSON not provided" if @expected_json.nil?
@actual, @expected = scrub(actual_json, @path), scrub(@expected_json)
flexible(parse_json(@expected)) == parse_json(@actual)
end
def flexible(hash)
hash.each do |key, value|
if value.is_a?(String) && value == '*'
hash[key] = NotNil.new
elsif value.is_a?(Hash)
hash[key] = flexible(value)
end
end
hash
end
end
class NotNil
def initialize
@compared = "<not compared>"
end
def ==(other)
@compared = other.nil? ? "*" : other
!other.nil?
end
def to_s
@compared.inspect
end
end
end
@jejacks0n
Copy link
Author

This allows specifying attributes that you want to ensure are there, but that you don't really care about the value of.

eg.

expect(response_body).to look_like <<-JSON
  {
    "access_token": "*",
    "token_type": "bearer",
  }
JSON

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment