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

Json-ify any non-string object in #to_return_json #1012

Merged
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
10 changes: 10 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -330,6 +330,16 @@ stub_request(:any, "www.example.com").
Net::HTTP.get('www.example.com', '/') # ===> "abc\n"
```

### Response with JSON body

```ruby

stub_request(:any, "www.example.com").
to_return_json(body: {foo: "bar"})

Net::HTTP.get('www.example.com', '/') # ===> "{\"foo\": \"bar\"}"
```

### Response with custom status message

```ruby
Expand Down
6 changes: 5 additions & 1 deletion lib/webmock/request_stub.rb
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,13 @@ def to_return_json(*response_hashes)

json_response_hashes = [*response_hashes].flatten.map do |resp_h|
headers, body = resp_h.values_at(:headers, :body)

body = body.call if body.respond_to?(:call)
body = body.to_json unless body.is_a?(String)

resp_h.merge(
headers: {content_type: 'application/json'}.merge(headers.to_h),
body: body.is_a?(Hash) ? body.to_json : body
body: body
)
end

Expand Down
26 changes: 26 additions & 0 deletions spec/unit/request_stub_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,32 @@
expect(@request_stub.response.status).to eq([500, ""])
end

it "should json-ify an Array body" do
@request_stub.to_return_json(body: [{abc: "def" }])
expect(@request_stub.response.body).to eq('[{"abc":"def"}]')
end

it "should json-ify any object responding to `to_json`" do
record = double("SomeRecord")
allow(record).to receive_messages(to_json: '{"what":"something"}.')

@request_stub.to_return_json(body: record)
expect(@request_stub.response.body).to eq('{"what":"something"}.')
end

it "should not over-json-ify a String body" do
@request_stub.to_return_json(body: '{"abc":"def"}')
expect(@request_stub.response.body).to eq('{"abc":"def"}')
end

it "should json-ify any callable proc or lambda to body" do
record = double("SomeRecord")
allow(record).to receive_messages(to_json: '{"what":"something callable"}.')

@request_stub.to_return_json(body: -> { record })
expect(@request_stub.response.body).to eq('{"what":"something callable"}.')
end

it "should apply the content_type header" do
@request_stub.to_return_json(body: {abc: "def"}, status: 500)
expect(@request_stub.response.headers).to eq({"Content-Type"=>"application/json"})
Expand Down