Lac*_*ter 28 rspec ruby-on-rails-3
基于我对rspec规范的理解,我希望通过以下示例.
describe ApplicationController do
controller do
def test
end
end
it "calls actions" do
get :test
end
end
Run Code Online (Sandbox Code Playgroud)
相反,它失败了:
No route matches {:controller=>"anonymous", :action=>"test"}
Run Code Online (Sandbox Code Playgroud)
我甚至尝试在路径文件中为"匿名"控制器定义路由,但无济于事.这里有什么我想念的吗?这应该工作,不应该吗?
Clu*_*ter 24
要在匿名控制器规范中使用自定义路由,您需要修改前一个块中的路由集.RSpec已经resources :anonymous
在before块中使用RESTful路由设置,并在after块中恢复原始路由.因此,要获得自己的路线,只需调用draw @routes
并添加所需内容即可.
这是一个ApplicationController
测试的规范的例子rescue_from CanCan::AccessDenied
require 'spec_helper'
describe ApplicationController
controller do
def access_denied
raise CanCan::AccessDenied
end
end
before do
@routes.draw do
get '/anonymous/access_denied'
end
end
it 'redirects to the root when access is denied' do
get :access_denied
response.should redirect_to root_path
end
it 'sets a flash alert when access is denied' do
get :access_denied
flash.alert.should =~ /not authorized/i
end
end
Run Code Online (Sandbox Code Playgroud)
更新
RSpec 2.12附近的处理得到了改善.如果您使用> 2.12,那么您不再需要挂钩@routes
.
Tim*_*m O 21
我遇到了类似的问题.在我的例子中,解决方案是在测试中的get请求中包含:id参数.
即
get :test, :id => 1
Run Code Online (Sandbox Code Playgroud)
检查您的路线,看看您是否缺少某个参数(可能是:id),然后将其添加到测试中.
似乎 rspec 为您提供了一组要使用的 RESTful 路由。因此,如果您只在匿名控制器中使用标准操作名称,则不会遇到此问题。迄今为止,我从来没有理由使用“索引”以外的任何东西。
describe ApplicationController do
describe 'respond_with_foo' do
controller do
def index
respond_with_foo
end
end
it 'should respond with foo' do
get :index
response.should be_foo
end
end
end
Run Code Online (Sandbox Code Playgroud)