【问题标题】:How to Set the Content Type in a ActionController::TestCase request如何在 ActionController::TestCase 请求中设置内容类型
【发布时间】:2011-07-24 15:44:51
【问题描述】:

我试图像这样在我的 TestCase 中执行 get:

request.env['CONTENT_TYPE'] = 'application/json'
get :index,:application_name=>"Heka"

虽然,它失败了:

ActionView::MissingTemplate: Missing template alarm_events/index with {:handlers=>[:builder, :haml, :erb, :rjs, :rhtml, :rxml], :locale=>[:en, :en], :formats=>[:html]

尽管在我的控制器中我有:

respond_to :html, :json

def index
    @alarm_events=[...]

    respond_with @alarm_events do |format|
      format.json{
        render :json=>@alarm_events.map{|e| e.to_portal_representation}.to_json, 
               :content_type=>'application/json'
      }
    end
  end

我到底应该如何在 TestCase 上编写预期的请求?

当我在浏览器中请求 alarm_events.json 时,它工作正常。

谢谢

【问题讨论】:

    标签: ruby-on-rails ruby json ruby-on-rails-3 rest


    【解决方案1】:
    @request.accept = 'application/json'
    

    【讨论】:

      【解决方案2】:

      我必须在参数中指定格式以进行动作控制器测试:

      get :index, {format: :json}
      

      【讨论】:

      • 如果您在路由表中提供默认格式(例如defaults: { format: :json }),这是正确的解决方案。您的 TestCase 请求不会通过路由表,因此它们不会附加该默认格式。
      【解决方案3】:

      我建议在 format.json 中设置标题

      def index
          @alarm_events=[...]
      
          respond_with @alarm_events do |format|
            format.json{
              render :json => @alarm_events.map{|e| e.to_portal_representation}.to_json, :content_type => 'application/json'
            }
          end
      

      【讨论】:

        猜你喜欢
        • 2018-05-26
        • 2012-04-07
        • 1970-01-01
        • 2015-08-18
        • 1970-01-01
        • 1970-01-01
        • 2021-05-16
        • 1970-01-01
        • 2015-07-19
        相关资源
        最近更新 更多