From cc4644f23bedb4d5357c1e3caafb44af2f03fcee Mon Sep 17 00:00:00 2001 From: Sebastien Savater Date: Fri, 19 May 2023 13:07:32 +0200 Subject: [PATCH] Json-ify procs in #to_return_json --- lib/webmock/request_stub.rb | 6 +++++- spec/unit/request_stub_spec.rb | 8 ++++++++ 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/lib/webmock/request_stub.rb b/lib/webmock/request_stub.rb index bd085b80..85d971a2 100644 --- a/lib/webmock/request_stub.rb +++ b/lib/webmock/request_stub.rb @@ -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 diff --git a/spec/unit/request_stub_spec.rb b/spec/unit/request_stub_spec.rb index 765027be..c8e3324d 100644 --- a/spec/unit/request_stub_spec.rb +++ b/spec/unit/request_stub_spec.rb @@ -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"})