这个问题可能已经在Stack Overflow上被问了十几次(例如(1),(2),(3),(4),( 5))但每次答案似乎都不同而且没有一个人帮助过我。我正在研究Rails引擎,我发现Rspec2有路由错误,但我可以在浏览器中找到路由。情况如下:
在引擎的routes.rb
:
resources :mw_interactives, :controller => 'mw_interactives', :constraints => { :id => /\d+/ }, :except => :show
# This is so we can build the InteractiveItem at the same time as the Interactive
resources :pages, :controller => 'interactive_pages', :constraints => { :id => /\d+/ }, :only => [:show] do
resources :mw_interactives, :controller => 'mw_interactives', :constraints => { :id => /\d+/ }, :except => :show
end
摘录rake routes
的输出:
new_mw_interactive GET /mw_interactives/new(.:format) lightweight/mw_interactives#new {:id=>/\d+/}
...
new_page_mw_interactive GET /pages/:page_id/mw_interactives/new(.:format) lightweight/mw_interactives#new {:id=>/\d+/, :page_id=>/\d+/}
我的测试,来自其中一个控制器规格(describe Lightweight::MwInteractivesController do
):
it 'shows a form for a new interactive' do
get :new
end
...得到这个结果:
Failure/Error: get :new
ActionController::RoutingError:
No route matches {:controller=>"lightweight/mw_interactives", :action=>"new"}
...但是当我在浏览器中访问该路线时,它的工作方式完全正常。
我在这里缺少什么?
ETA:澄清一点安德烈亚斯提出:这是一个Rails引擎,因此rspec在虚拟应用程序中运行,该应用程序包含命名空间中引擎的路由:
mount Lightweight::Engine => "/lightweight"
...因此rake routes
中显示的路线以/lightweight/
开头。这就是为什么Rspec错误中显示的路线似乎与rake routes
中的路线不匹配的原因。但它确实使调试变得更加困难。
ETA2:回答Ryan Clark的评论,这是我正在测试的行动:
module Lightweight
class MwInteractivesController < ApplicationController
def new
create
end
......就是这样。
答案 0 :(得分:1)
我找到了解决方法。在规范的顶部,我添加了这段代码:
render_views
before do
# work around bug in routing testing
@routes = Lightweight::Engine.routes
end
...现在规范在没有路由错误的情况下运行。但是我不知道为什么会这样,所以如果有人能发一个解释它的答案,我会接受的。
答案 1 :(得分:0)
我认为你的规格可能会出现问题
“轻量级”如何进入这一行:controller =&gt;“lightweight / mw_interactives”
路线说
new_mw_interactive GET /mw_interactives/new(.:format)
不是
new_mw_interactive GET /lightweight/mw_interactives/new(.:format)
答案 2 :(得分:0)
添加文件spec / routing / root_routing_spec.rb
require "spec_helper"
describe "routes for Widgets" do
it "routes /widgets to the widgets controller" do
{ :get => "/" }.should route_to(:controller => "home", :action => "index")
end
end
然后添加文件spec / controllers / home_controller_spec.rb
require 'spec_helper'
describe HomeController do
context "GET index" do
before(:each) do
get :index
end
it {should respond_with :success }
it {should render_template(:index) }
end
end