2011-03-28 47 views
5

我試圖在我的TestCase這樣執行GET:如何設置內容類型中的ActionController :: TestCase的要求

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時,它工作正常。

感謝

回答

8

我必須指定在PARAMS的動作控制器測試格式:

get :index, {format: :json} 
+0

如果您在路由表中提供默認格式(例如'defaults:{format::json}'),這是正確的解決方案。你的'TestCase'請求不通過路由表,因此它們不會有附加的默認格式。 – piersadrian 2014-02-23 00:31:39

2

我會建議設置頁眉的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 
+0

Nop。它仍然不起作用。問題已更新。 – 2011-03-28 17:00:08

6
@request.accept = 'application/json' 
相關問題