Created
January 21, 2011 03:44
-
-
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)
This file contains 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
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 |
This file contains 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_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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Assuming the API call failed, you'd get an error something like:
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 ==)