2010-03-01 55 views
31

如果你的控制器動作看起來是這樣的:在Rails中,你如何測試Javascript響應格式的功能?

respond_to do |format| 
    format.html { raise 'Unsupported' } 
    format.js # index.js.erb 
end 

和你的功能測試是這樣的:

test "javascript response..." do 
    get :index 
end 

它將執行respond_to代碼塊的HTML分支。

如果你試試這個:

test "javascript response..." do 
    get 'index.js' 
end 

它執行不運行的控制器動作視圖(index.js.erb的)!

回答

55

將您的正常參數傳入:format以觸發該格式的響應。

get :index, :format => 'js' 

沒有必要弄亂您的請求標題。

+2

請注意,在Rails 3中,您可以使用符號,看起來整潔。 'get:index,format::js' – dazonic 2012-05-07 07:08:23

+9

@dazonic你確定這不僅僅是由於Ruby 1.9嗎? – 2013-02-08 21:47:14

+0

2016更新:https://github.com/rspec/rspec-rails/issues/950。它會引發InvalidCrossOriginRequest錯誤。使用@steven的答案:) – 2016-05-06 11:53:59

3

使用此請求之前:

@request.env['HTTP_ACCEPT'] = 'text/javascript' 
5

將接受的內容類型的類型你想要的:

@request.accept = "text/javascript" 

get :index測試結合這一點,它將使控制器適當的呼叫。

25

使用RSpec:

it "should render js" do 
    xhr :get, 'index' 
    response.content_type.should == Mime::JS 
end 

,並在你的控制器動作:

1

這三個看似等效:

  1. get :index, :format => 'js'
  2. @request.env['HTTP_ACCEPT'] = 'text/javascript'
  3. @request.accept = "text/javascript"

它們造成控制器使用一個js模板(例如index.js.erb的)

而模擬一個XHR請求(例如獲得HTML代碼段),您可以使用此: @request.env['HTTP_X_REQUESTED_WITH'] = "XMLHttpRequest"

這意味着request.xhr?將返回true。

需要注意的是,模擬XHR的時候,我必須指定預期的格式或我得到了一個錯誤:

get :index, format: "html"

測試on Rails的3.0.3。

我得到了後者從Rails的來源,在這裏:https://github.com/rails/rails/blob/6c8982fa137421eebdc55560d5ebd52703b65c65/actionpack/lib/action_dispatch/http/request.rb#L160

+1

要模擬一個XHR請求,而不是搞亂@ request.env,最好使用提供的helper:xhr:get,:index,format:「html」 – Nick 2013-08-09 18:23:04

0

這樣使用代碼參數和用戶ID等,注意格式選項是在其他參數,如ID和nested_attributes的相同的哈希。

put :update, {id: record.id, nested_attributes: {id: 1, name: "John"}, format: :js}, user.id 
0

以上答案中的很多都過時了。

在RSpec 3+中執行此操作的正確方法是post some_path, xhr: true

棄用警告直接從RSpec的本身,當試圖使用xhr :post, "some_path"

DEPRECATION WARNING: `xhr` and `xml_http_request` are deprecated and will be removed in Rails 5.1. 
Switch to e.g. `post comments_path, params: { comment: { body: 'Honey bunny' } }, xhr: true`. 

此外,xhr :post, "some_path"導致一些時髦的錯誤,不post some_path, xhr: true發生。

相關問題