Created
September 7, 2012 16:53
-
-
Save mbleigh/3667733 to your computer and use it in GitHub Desktop.
RSpec matcher for JSON responses.
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
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 |
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
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