File tree Expand file tree Collapse file tree 3 files changed +41
-1
lines changed Expand file tree Collapse file tree 3 files changed +41
-1
lines changed Original file line number Diff line number Diff line change @@ -330,6 +330,16 @@ stub_request(:any, "www.example.com").
330
330
Net ::HTTP .get(' www.example.com' , ' /' ) # ===> "abc\n"
331
331
```
332
332
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
+
333
343
### Response with custom status message
334
344
335
345
``` ruby
Original file line number Diff line number Diff line change @@ -29,9 +29,13 @@ def to_return_json(*response_hashes)
29
29
30
30
json_response_hashes = [ *response_hashes ] . flatten . map do |resp_h |
31
31
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
+
32
36
resp_h . merge (
33
37
headers : { content_type : 'application/json' } . merge ( headers . to_h ) ,
34
- body : body . is_a? ( Hash ) ? body . to_json : body
38
+ body : body
35
39
)
36
40
end
37
41
Original file line number Diff line number Diff line change 69
69
expect ( @request_stub . response . status ) . to eq ( [ 500 , "" ] )
70
70
end
71
71
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
+
72
98
it "should apply the content_type header" do
73
99
@request_stub . to_return_json ( body : { abc : "def" } , status : 500 )
74
100
expect ( @request_stub . response . headers ) . to eq ( { "Content-Type" => "application/json" } )
You can’t perform that action at this time.
0 commit comments