Jacob Eiler
Jacob Eiler

Reputation: 31

How to set request_id in Rails test

I have some code that relies on request_id being set, but when testing in RSpec 3.8 and Rails 5.1 request_id is not set. It works in development and production.

I have tried setting the X-Request-Id header manually in the spec file, but it does not work.

I am not sure if it is a Rails issue in the test environment or whether it is caused by RSpec.

In my spec:

request.headers.add('X-Request-Id', SecureRandom.uuid)
patch model_update_path(model), params: { model: { attr: 'changed' }}
... # actual tests

and in my controller

...
def update
  logger.info "Request Id: #{request.request_id}"
  logger.info "X-Request-Id: #{request.header['X-Request-Id']}"
  ... # actual logic
end
...

The first line logs nothing, while the second logs the random uuid.

I expected the request.request_id method to return a unique uuid for each request in the test environment.

Upvotes: 3

Views: 1323

Answers (2)

rya brody
rya brody

Reputation: 286

You could stub the method request_id of all instances from the class ActionController::TestRequest:

allow_any_instance_of(ActionController::TestRequest).to receive(:request_id).and_return(SecureRandom.uuid)
patch model_update_path(model), params: { model: { attr: 'changed' }}

Upvotes: 0

Mohamed Ziata
Mohamed Ziata

Reputation: 1226

Try this:

patch model_update_path(model), { params: { model: { attr: 'changed' }, 'X-Request-Id' => SecureRandom.uuid }

Upvotes: 1

Related Questions