Skip to content

Commit

Permalink
Merge pull request #1012 from inkstak/feature-to_return_json_accepts_…
Browse files Browse the repository at this point in the history
…array_body

Json-ify any non-string object in #to_return_json
  • Loading branch information
bblimke authored Aug 19, 2023
2 parents 0d422a1 + cc4644f commit d933001
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 1 deletion.
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

0 comments on commit d933001

Please sign in to comment.