Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Error on invalid body #427

Merged
merged 2 commits into from
Nov 2, 2014
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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