Skip to content

Commit

Permalink
Json-ify procs in #to_return_json
Browse files Browse the repository at this point in the history
  • Loading branch information
inkstak committed May 19, 2023
1 parent d1e55fa commit cc4644f
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 1 deletion.
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?(String) ? body : body.to_json
body: body
)
end

Expand Down
8 changes: 8 additions & 0 deletions spec/unit/request_stub_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,14 @@
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 cc4644f

Please sign in to comment.