Skip to content

Instantly share code, notes, and snippets.

@jamesmartin
Created January 21, 2011 03:44
Show Gist options
  • Save jamesmartin/789207 to your computer and use it in GitHub Desktop.
Save jamesmartin/789207 to your computer and use it in GitHub Desktop.
An example custom RSpec matcher that makes describing expectations on HTTP failures nicer and gives more information when it fails (like the response body)
require 'spec_helper'
describe "Fun REST API Function" do
before(:each) do
@api = FunRestApi.new
end
context "when creating a valid widget" do
it "responds with a success message" do
response = @api.post(Widget.new("some widget"))
response.should have_http_status_code '200'
end
end
end
RSpec::Matchers.define :have_http_status_code do |status_code|
match do |http_response|
http_response.code.should == status_code
end
failure_message_for_should do |http_response|
"Got HTTP status code '#{http_response.code}' but expected '#{status_code}'. \nThe response body was:\n#{http_response.body}"
end
end
@jamesmartin
Copy link
Author

Assuming the API call failed, you'd get an error something like:

 Failure/Error: response.should have_http_status_code '200'
 Got HTTP status code '400' but expected '200'. 
 The response body was:
 <?xml version="1.0" encoding="utf-8"?><ApiError><Code>666</Code><Message>Invalid Widget!</Message></ApiError>

As opposed to the alternative test code:
...
response.code.should == '200'
...

And the corresponding failure message:
Failure/Error: raw_api_response.code.should == '200'
expected: "200",
got: "400" (using ==)

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