Skip to content

Commit

Permalink
Added automatic HTTP status code checking.
Browse files Browse the repository at this point in the history
  • Loading branch information
dbalatero committed Apr 29, 2010
1 parent 0a40a9a commit 005fc4b
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 2 deletions.
13 changes: 11 additions & 2 deletions lib/monster_mash/base.rb
@@ -1,4 +1,8 @@
module MonsterMash
class HTTPError < StandardError
attr_accessor :response
end

class Base
include ClassLevelInheritableAttributes
inheritable_attributes :defaults
Expand Down Expand Up @@ -60,8 +64,13 @@ def #{name}(*args, &block)
end
end

def inherited(subclass)

def self.check_response_and_raise!(response)
code = response.code.to_i
if code < 200 or code >= 400
error = MonsterMash::HTTPError.new("Got bad HTTP response! code: #{code}")
error.response = response
raise error
end
end

private
Expand Down
37 changes: 37 additions & 0 deletions spec/monster_mash/base_spec.rb
Expand Up @@ -67,6 +67,43 @@ class C < A
end
end

describe "#check_response_and_raise!" do
before(:each) do
@response = mock('response')
end

it "should raise if a response has a code in the wrong range" do
bad_codes = [0, 404, 500, 403, 410, 400]
bad_codes.each do |code|
@response.stub!(:code).and_return(code)
lambda {
MonsterMash::Base.check_response_and_raise!(@response)
}.should raise_error(MonsterMash::HTTPError)
end
end

it "should not raise if a response has good codes" do
good_codes = [200, 204, 301, 302]
good_codes.each do |code|
@response.stub!(:code).and_return(code)
lambda {
MonsterMash::Base.check_response_and_raise!(@response)
}.should_not raise_error(MonsterMash::HTTPError)
end
end

it "should propagate the response object with the error" do
@response.stub!(:code).and_return(400)
error = nil
begin
MonsterMash::Base.check_response_and_raise!(@response)
rescue => e
error = e
end
error.response.should == @response
end
end

describe "#delete" do
it "should proxy to build_method" do
MockApi.should_receive(:build_method).
Expand Down

0 comments on commit 005fc4b

Please sign in to comment.