【问题标题】:How to set fake request object for rails controller object如何为 Rails 控制器对象设置假请求对象
【发布时间】:2020-04-30 14:18:43
【问题描述】:

我需要在控制器外使用 render_to_string 方法。 所以我创建了控制器实例:

  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)

但它失败了,因为里面的请求对象是零。你能帮我吗?如何为控制器对象创建虚假请求?

【问题讨论】:

    标签: ruby-on-rails applicationcontroller render-to-string


    【解决方案1】:

    基于this blog post env 参数看起来像

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

    由于 Rails 不允许将空映射作为 env 参数,因此创建请求对象的最少代码为

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

    【讨论】:

      【解决方案2】:

      已解决。

      添加

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

      现在看起来像

            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)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-02-04
        • 2015-10-09
        • 1970-01-01
        • 1970-01-01
        • 2011-08-08
        • 1970-01-01
        • 2015-03-12
        • 2013-09-12
        相关资源
        最近更新 更多