Search code examples
ruby-on-railsapplicationcontrollerrender-to-string

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?


Solution

  • 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)