簡體   English   中英

使用rspec測試常規控制器操作

[英]Testing a general controller action using 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。 測試此控制器操作的最佳方法是什么?

你是現貨。 問題是你正在尋找一條沒有: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

您需要一個映射到控制器操作的路徑

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM