[英]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.