使用rspec测试常规控制器操作

时间:2013-11-21 18:37:38

标签: ruby-on-rails 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。测试此控制器操作的最佳方法是什么?

2 个答案:

答案 0 :(得分:3)

你是真的。问题是你正在寻找一条没有:id的路线,但你没有路线。您需要将参数传递给post :save_tags的{​​{1}},并且考虑到上述问题,我相信这就是您所说的:id

因此,请尝试将测试更改为:

article_id

<强>更新

Rails可能会因为你在你的路线中使用describe ArticleController do context 'saving tags' do post :save_tags, tag_id => 123, id => 1234 # tests here end end 而感到困惑,我相信:action是一个保留字或Rails视为特殊的字。也许尝试将您的路线更改为:

action

你的测试:

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

答案 1 :(得分: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