Skip to content

Apply Net::HTTP response_body_encoding to stubbed response bodies - #1138

Merged
bblimke merged 1 commit into
bblimke:masterfrom
ybai08:net-http-response-body-encoding
Nov 20, 2026
Merged

bblimke merged 1 commit into
bblimke:masterfrom
ybai08:net-http-response-body-encoding

Conversation

@ybai08

@ybai08 ybai08 commented Oct 17, 2026

Copy link
Copy Markdown
Contributor

Fixes #1028

Net::HTTP (net-http 0.2+, Ruby 3.0+) can set the encoding of response bodies, either for every request with Net::HTTP#response_body_encoding= or per response with Net::HTTPResponse#body_encoding=. true detects the encoding from the Content-Type charset or an HTML <meta> tag; an Encoding or encoding name forces that encoding. Net::HTTP#transport_request copies the setting onto each response, and Net::HTTPResponse#read_body applies it to the body it reads.

Stubbed responses skipped both steps, so with WebMock the body always kept the encoding it was stubbed with. The body was usually BINARY when it came from a raw response file or curl -is output, as in the issue:

stub_request(:get, "www.example.com")
  .to_return(body: "caf\xC3\xA9".b, headers: {"Content-Type" => "text/plain; charset=utf-8"})

http = Net::HTTP.new("www.example.com", 80)
http.response_body_encoding = true
http.request(Net::HTTP::Get.new("/")).body.encoding
# real Net::HTTP: UTF-8
# WebMock before: ASCII-8BIT
# WebMock after:  UTF-8

The change:

  • build_net_http_response copies response_body_encoding onto the stubbed response, as transport_request does. It is guarded with respond_to?, so Rubies without the setting (2.6, 2.7) are unaffected.
  • Net::WebMockHTTPResponse#read_body applies @body_encoding the same way Net::HTTPResponse#read_body does when the body is read without a block or destination. Because this happens when the body is read, setting res.body_encoding = "UTF-8" inside a request block also works, as the Net::HTTP docs show. The body is duplicated before force_encoding, so the stored stub body is never changed. When the setting is false (the default), nothing changes.

The issue suggested making ResponseFactory.response_for always detect the charset. I didn't do that: real Net::HTTP returns bodies as-is unless the client asks for an encoding, so detecting the charset by default would make stubs differ from real responses. With this change, the raw-response case from the issue gets the charset as soon as the client turns on response_body_encoding.

Streaming with read_body { |segment| ... } is unchanged: segments are still the raw stubbed bytes, as they are with real Net::HTTP. (Real Net::HTTP then raises NoMethodError on Net::ReadAdapter#force_encoding when an encoding is set. WebMock does not copy that.)

Testing

  • Added specs under Net:HTTP response body encoding in spec/acceptance/net_http/net_http_spec.rb. They cover: the default stays unchanged; true with a Content-Type charset; true with a <meta charset>; a forced encoding name; body_encoding= set on the response inside the request block; and the stub body not being changed between requests. Four of the six fail without the change and all pass with it.
  • Compared stubbed and real responses from a local WEBrick server on Ruby 4.0.7. The bodies were UTF-8, ISO-8859-1, no charset, HTML <meta> and empty. The settings were true, Encoding::UTF_8 and "ISO-8859-1", each with and without a request block. The encodings now match in all 30 combinations. Before the change, 28 of them differed: every one except true with no charset, where real Net::HTTP leaves the body unchanged.
  • bundle exec rake spec on Ruby 4.0.7: 5691 examples, 142 failures. The same 142 examples fail on master without this change. All of them make real requests to outside hosts (TLS and connection errors in this environment).
  • bundle exec rake spec_http_without_webmock, rake test and rake minitest all pass.
  • Not run: other Ruby versions in the CI matrix (in particular 2.6/2.7, where the respond_to? and defined? guards keep the old behaviour) and JRuby.

I didn't add a CHANGELOG entry, because entries seem to be written at release time. I can add one if you'd like.

Net::HTTP forces the encoding chosen with Net::HTTP#response_body_encoding=
or Net::HTTPResponse#body_encoding= onto the body it reads, detecting it
from the Content-Type charset or a meta tag when the setting is true.
Stubbed responses ignored the setting and always returned the body in the
encoding it was stubbed with.

Fixes bblimke#1028
@bblimke
bblimke merged commit 14defa9 into bblimke:master Nov 20, 2026
8 checks passed
bblimke added a commit that referenced this pull request Nov 20, 2026
Net::HTTP applies the body encoding once, when it reads the body, which
happens in the request block or right after it. The stubbed response
applied it at the first read of the body instead, so a body_encoding=
set after request returned still took effect, and read_body with a
string buffer left the buffer binary. Apply it when the request block
returns too, apply it to a string buffer, and ignore later changes to
the setting. Detect the encoding from the raw bytes, as Net::HTTP does,
so a stubbed body tagged with another encoding does not raise, and
leave alone a frozen body assigned in the request block.

Real responses that pass through WebMock keep the encoding Net::HTTP
gave them, as before #1138. Applying it again ran the detection twice
and raised ArgumentError for a body that was invalid in its new
encoding.

Give each stubbed response its own copy of the body, so the encoding is
forced in place as Net::HTTP does it. That also stops a frozen stubbed
body making response.body frozen, and changes to response.body reaching
later requests to the same stub.

Fold the repeated request setup in the specs into a helper, add specs
for the cases above, and document #1138 and the copied body in the
CHANGELOG.
@bblimke

bblimke commented Nov 20, 2026

Copy link
Copy Markdown
Owner

Thank you @ybai08! This is released in 3.36.0. I made a few changes on top, so stubbed responses behave like real Net::HTTP ones:

  • The encoding is applied once, when the body is read or the request block returns. A body_encoding= set later is ignored, as in Net::HTTP.
  • A string passed to read_body gets the encoding too.
  • Real responses keep the encoding Net::HTTP gave them.
  • Each stubbed response gets its own copy of the body, so a frozen stubbed body no longer raises FrozenError.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Allow setting Net::HTTP#response_body_encoding

2 participants