Kirill Berlin
Kirill Berlin

Reputation: 49

How to set fake request object for rails controller object

I need to use render_to_string method outside the controller. So I create controller instance like:

  controller = class_name.constantize.new # Rails controller instance
  controller.params = params
  controller.action_name = 'index'
  controller.create_global_current_user user
  index_render_options = controller.send('index_render_options')
  controller.send('render_to_string', index_render_options)

But it fails because request object inside is nil. Could you help me with it? how to create fake request for controller object?

Upvotes: 0

Views: 2293

Answers (2)

bottlenecked
bottlenecked

Reputation: 2157

Based on this blog post the env parameter looks like

env = {
  'REQUEST_METHOD' => 'GET',
  'PATH_INFO' => '/hello',
  'HTTP_HOST' => 'skylight.io',
  # ...
}

Since Rails does not allow an empty map as the env parameter, the minimum code for creating a request object would be

request = ActionDispatch::Request.new({ "REQUEST_METHOD" => "GET" })

Upvotes: 0

Kirill Berlin
Kirill Berlin

Reputation: 49

SOLVED.

Added

  controller.request = ActionDispatch::Request.new({})
  resp = controller.class.make_response!(controller.request)
  controller.set_response!(resp)

so now it looks like

      controller = class_name.constantize.new
      controller.params = params
      controller.action_name = 'index'
      controller.request = ActionDispatch::Request.new({})
      resp = controller.class.make_response!(controller.request)
      controller.set_response!(resp)
      controller.create_global_current_user user
      index_render_options = controller.send('index_render_options')
      controller.send('render_to_string', index_render_options)

Upvotes: 0

Related Questions