Skip to content

Commit d933001

Browse files
authored
Merge pull request #1012 from inkstak/feature-to_return_json_accepts_array_body
Json-ify any non-string object in #to_return_json
2 parents 0d422a1 + cc4644f commit d933001

File tree

3 files changed

+41
-1
lines changed

3 files changed

+41
-1
lines changed

README.md

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -330,6 +330,16 @@ stub_request(:any, "www.example.com").
330330
Net::HTTP.get('www.example.com', '/') # ===> "abc\n"
331331
```
332332

333+
### Response with JSON body
334+
335+
```ruby
336+
337+
stub_request(:any, "www.example.com").
338+
to_return_json(body: {foo: "bar"})
339+
340+
Net::HTTP.get('www.example.com', '/') # ===> "{\"foo\": \"bar\"}"
341+
```
342+
333343
### Response with custom status message
334344

335345
```ruby

lib/webmock/request_stub.rb

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,9 +29,13 @@ def to_return_json(*response_hashes)
2929

3030
json_response_hashes = [*response_hashes].flatten.map do |resp_h|
3131
headers, body = resp_h.values_at(:headers, :body)
32+
33+
body = body.call if body.respond_to?(:call)
34+
body = body.to_json unless body.is_a?(String)
35+
3236
resp_h.merge(
3337
headers: {content_type: 'application/json'}.merge(headers.to_h),
34-
body: body.is_a?(Hash) ? body.to_json : body
38+
body: body
3539
)
3640
end
3741

spec/unit/request_stub_spec.rb

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,32 @@
6969
expect(@request_stub.response.status).to eq([500, ""])
7070
end
7171

72+
it "should json-ify an Array body" do
73+
@request_stub.to_return_json(body: [{abc: "def" }])
74+
expect(@request_stub.response.body).to eq('[{"abc":"def"}]')
75+
end
76+
77+
it "should json-ify any object responding to `to_json`" do
78+
record = double("SomeRecord")
79+
allow(record).to receive_messages(to_json: '{"what":"something"}.')
80+
81+
@request_stub.to_return_json(body: record)
82+
expect(@request_stub.response.body).to eq('{"what":"something"}.')
83+
end
84+
85+
it "should not over-json-ify a String body" do
86+
@request_stub.to_return_json(body: '{"abc":"def"}')
87+
expect(@request_stub.response.body).to eq('{"abc":"def"}')
88+
end
89+
90+
it "should json-ify any callable proc or lambda to body" do
91+
record = double("SomeRecord")
92+
allow(record).to receive_messages(to_json: '{"what":"something callable"}.')
93+
94+
@request_stub.to_return_json(body: -> { record })
95+
expect(@request_stub.response.body).to eq('{"what":"something callable"}.')
96+
end
97+
7298
it "should apply the content_type header" do
7399
@request_stub.to_return_json(body: {abc: "def"}, status: 500)
74100
expect(@request_stub.response.headers).to eq({"Content-Type"=>"application/json"})

0 commit comments

Comments
 (0)