Skip to content

Commit

Permalink
Fixed type checking in WebMock::Response#assert_valid_body! to correc…
Browse files Browse the repository at this point in the history
…tly identify Hash objects and improved error message.
  • Loading branch information
bblimke committed Feb 20, 2024
1 parent 9b2bef0 commit f7080b5
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 6 deletions.
8 changes: 4 additions & 4 deletions lib/webmock/response.rb
Original file line number Diff line number Diff line change
Expand Up @@ -117,11 +117,11 @@ def assert_valid_body!
return if @body.nil?
return if valid_types.any? { |c| @body.is_a?(c) }

if @body.class.is_a?(Hash)
raise InvalidBody, "must be one of: #{valid_types}, but you've used a #{@body.class}' instead." \
"\n What shall we encode it to? try calling .to_json .to_xml instead on the hash instead, or otherwise convert it to a string."
if @body.is_a?(Hash)
raise InvalidBody, "must be one of: #{valid_types}, but you've used a #{@body.class}. " \
"Please convert it by calling .to_json .to_xml, or otherwise convert it to a string."
else
raise InvalidBody, "must be one of: #{valid_types}. '#{@body.class}' given"
raise InvalidBody, "must be one of: #{valid_types}. '#{@body.class}' given."
end
end

Expand Down
8 changes: 6 additions & 2 deletions spec/unit/response_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -140,12 +140,16 @@
#
it "should error if given a non-allowed type: a hash" do
expect { WebMock::Response.new(body: Hash.new) }.to \
raise_error(WebMock::Response::InvalidBody)
raise_error(
WebMock::Response::InvalidBody,
"must be one of: [Proc, IO, Pathname, String, Array], but you've used a Hash. Please convert it by calling .to_json .to_xml, or otherwise convert it to a string."
)
end

it "should error if given a non-allowed type: something that is not a hash" do
expect { WebMock::Response.new(body: 123) }.to \
raise_error(WebMock::Response::InvalidBody)
raise_error(WebMock::Response::InvalidBody,
"must be one of: [Proc, IO, Pathname, String, Array]. 'Integer' given.")
end
end

Expand Down

0 comments on commit f7080b5

Please sign in to comment.