没有路由匹配rspec的匿名控制器

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),然后将其添加到测试中.

  • 好的,经过进一步调查,这似乎是一个部分解决方案.包含:id参数将使规范工作 - 但前提是您正在使用需要ID的标准RESTful操作名称之一.如果您使用任意操作名称,例如'test',那么无论如何都会出现路由错误.看起来Rails和RSpec在这个领域做了太多的假设.控制器测试应测试控制器.我们有路由的路由规范. (6认同)
  • 啊〜对了〜这是有意义的,因为我发现索引和创建动作似乎工作,而任何其他名称得到路由错误(这些动作不需要ID).我会进一步查看. (2认同)
  • 对于rails 3.1.0和rspec 2.7.0仍然如此.我同意你的意见 - 为什么假设我的行动名称? (2认同)

Wil*_*ins 5

似乎 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)