2013-11-21 89 views
4

這裏是我的路線怎麼看起來像一個普通的控制器操作:測試使用RSpec的

/article/:id/:action  {:root=>"article", :controller=>"article/article", :title=>"Article"} 

這裏是我的控制器看起來像:

# app/controllers/article/article_controller.rb 
class ArticleController < ApplicationController 
    def save_tags 
    # code here 
    end 
end 

我想測試save_tags動作,所以我寫我的規格像這樣:

describe ArticleController do  
    context 'saving tags' do 
    post :save_tags, tag_id => 123, article_id => 1234 
    # tests here 
    end 
end 

但是當我運行這個天賦,我得到的錯誤

ActionController::RoutingError ... 
No route matches {:controller=>"article/article", :action=>"save_tags"} 

我認爲問題是save_tags操作是一個通用控制器操作,即。路由中沒有/ article /:id/save_tags。測試此控制器操作的最佳方法是什麼?

回答

3

你是在找。問題是你正在尋找一個沒有:id的路線,但你沒有。您需要將參數傳遞給post :save_tags:id,並且鑑於上述問題,我相信這就是您要求的article_id

因此,嘗試改變你的測試:

describe ArticleController do  
    context 'saving tags' do 
    post :save_tags, tag_id => 123, id => 1234 
    # tests here 
    end 
end 

更新

Rails的可能,因爲你使用你的路線:action,我相信action越來越困惑或者是保留字,或者一個Rails認爲特殊的詞。也許嘗試改變你的路線:

/article/:id/:method_name {:root=>"article", :controller=>"article/article", :title=>"Article"}

而且你的測試:

describe ArticleController do  
    context 'saving tags' do 
    post :save_tags, { :tag_id => 123, :article_id => 1234, :method_name => "save_tags" } 
    # tests here 
    end 
end 
+0

感謝您的迴應CDub。我試過了上面的測試,但是我仍然遇到同樣的錯誤:沒有路由匹配{:tag_id => 123,:action =>「save_tags」,:controller =>「article/article」,:id => 1234} – User314159

+0

我不願意在你的路由中使用':action',因爲Rails可能會對你的路由意味着什麼感到困惑......也許嘗試在你的路由中更改':action'到':method_name',然後傳入':method_name =>「save_tags」'在你的測試中...我會做一個編輯來顯示這個。 – CDub

0

您需要的路由映射到控制器的動作

post '/article/:id/save_tags' 

應該工作,或考慮利用資源幫手打造您的路線

# creates the routes new, create, edit, update, show, destroy, index 
resources :articles 

# you can exclude any you do not want 
resources :articles, except: [:destroy] 

# add additional routes that require an article in the member block 
resources :articles do 
    member do 
    post 'save_tags' 
    end 
end 

# add additional routes that do NOT require an article in the collection block 
resources :articles do 
    collection do 
    post 'publish_all' 
    end 
end