Rails tests: Content-Length header before sending it

Here is a quick and easy way to estimate the content-length of a request from the params being sent.

I needed to do this recently in a Rails test.

require 'rack'

params = { mike: true }
params_string = Rack::Utils.build_nested_query(params)
content_length = params_string.length

puts content_length
# 9

Keep in mind, the actual content-length could end up slightly larger depending on what else is being sent in the request.

If you're only needing to know the size of the params argument, then this method takes care of it for you.