Skip to content

Instantly share code, notes, and snippets.

@bitmage
Created November 17, 2010 03:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bitmage/702958 to your computer and use it in GitHub Desktop.
Save bitmage/702958 to your computer and use it in GitHub Desktop.
Assertion class for testing JSON content.
class HaveJson
def initialize(selector)
@selector = selector
end
def matches?(json)
@json = json
return traverse(@json, @selector)
end
def description
"find selector in JSON"
end
def failure_message
"Expected JSON to include: #{@selector}.\nClosest node found: #{@last_node}.\n" + actual
end
def actual
@actual.present? ? "Test: #{@test} Actual: #{@actual}\n" : ""
end
def negative_failure_message
"Found: #{@selector} in JSON string. Expected nil."
end
private
def traverse(json, path)
path.split('/').inject(json) do |value, selector|
if selector.include? '='
selector, test = selector.split('=')
set_value(value, selector)
unless value.to_s == test
@test = test
@actual = value.to_s
return nil
end
else
set_value(value, selector)
end
end
end
def set_value(value, selector)
value = value[selector] rescue nil
@last_node = selector
end
end
def have_json(selector)
HaveJson.new(selector)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment