Skip to content

Instantly share code, notes, and snippets.

@mbleigh
Created September 7, 2012 16:53
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mbleigh/3667733 to your computer and use it in GitHub Desktop.
Save mbleigh/3667733 to your computer and use it in GitHub Desktop.
RSpec matcher for JSON responses.
RSpec::Matchers.define :have_json_key do |expected_key|
match do |response|
@body = MultiJson.load(response.body)
result = @body.key?(expected_key.to_s)
result &&= @body[expected_key.to_s] == @expected_val if @val_provided
result
end
chain :with_value do |val|
@val_provided = true
@expected_val = val
end
description do
result = "have json key #{expected_key.inspect}"
result << " with value #{@expected_val.inspect}" if @val_provided
result
end
failure_message_for_should do |actual|
"expected response " + description + ", was #{@body[expected_key.to_s].inspect}"
end
end
describe "users api" do
it "should display the name" do
user = build(:user, name: "Bob Bobson")
User.stub!(find: user)
get '/users/123'
last_response.should have_json_key(:name).with_value("Bob Bobson")
end
emd
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment