Skip to content

Commit

Permalink
Merge pull request #427 from covermymeds/error-on-invalid-body
Browse files Browse the repository at this point in the history
Error on invalid body
  • Loading branch information
bblimke committed Nov 2, 2014
2 parents 3e9562e + 6f62fb7 commit 94d71c7
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 1 deletion.
10 changes: 10 additions & 0 deletions lib/webmock/response.rb
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ def body

def body=(body)
@body = body
assert_valid_body!
stringify_body!
end

Expand Down Expand Up @@ -109,6 +110,13 @@ def stringify_body!
end
end

def assert_valid_body!
valid_types = [Proc, IO, Pathname, String, Array]
return if @body.nil?
return if valid_types.any? { |c| @body.is_a?(c) }
raise InvalidBody, "must be one of: #{valid_types}. '#{@body.class}' given"
end

def read_raw_response(raw_response)
if raw_response.is_a?(IO)
string = raw_response.read
Expand All @@ -129,6 +137,8 @@ def read_raw_response(raw_response)
options
end

InvalidBody = Class.new(StandardError)

end

class DynamicResponse < Response
Expand Down
2 changes: 1 addition & 1 deletion spec/unit/request_pattern_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -400,7 +400,7 @@ def match(request_signature)
:headers => {:content_type => 'application/json'}, :body => "foo bar"))
end

it "shound not match if request body is different" do
it "should not match if request body is different" do
WebMock::RequestPattern.new(:post, 'www.example.com', :body => {:a => 1, :b => 2}).
should_not match(WebMock::RequestSignature.new(:post, "www.example.com",
:headers => {:content_type => 'application/json'}, :body => "{\"a\":1,\"c\":null}"))
Expand Down
9 changes: 9 additions & 0 deletions spec/unit/response_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,15 @@
@response = WebMock::Response.new(:body => Pathname.new(__FILE__))
@response.body.should == File.read(__FILE__)
end

# Users of webmock commonly make the mistake of stubbing the response
# body to return a hash, to prevent this:
#
it "should error if not given one of the allowed types" do
lambda { WebMock::Response.new(:body => Hash.new) }.should \
raise_error(WebMock::Response::InvalidBody)
end

end

describe "from raw response" do
Expand Down

0 comments on commit 94d71c7

Please sign in to comment.