我正在Rails 3.0.12下构建一个Rails引擎,但我在尝试为引擎的控制器编写规范时遇到路由问题。
我一直在关注Enginex布局。该引擎名为Featuring
,并且不是隔离的。它不会单独声明路由:没有featuring/config/routes.rb
文件。相反,为主应用程序提供了routes_for_feature
方法来定义特定于引擎的路由。
##
# featuring/lib/featuring/rails.rb
#
require 'featuring/rails/routing'
module Featuring
class Engine < ::Rails::Engine
end
end
##
# featuring/lib/featuring/rails/routing.rb
#
module ActionDispatch::Routing
class Mapper
def routes_for_feature(feature_name)
resource_name = feature_name.to_s.pluralize.to_sym
resources resource_name, :controller => "featuring/features", :only => [:index, :show], :feature => feature_name.to_s
end
end
end
按照Enginex模板,我有一个Dummy
应用程序,它定义了路由:
# featuring/spec/dummy/config/routes.rb
Dummy::Application.routes.draw do
routes_for_feature :feature_model
end
当我为Dummy
应用运行rails服务器时,一切正常。我可以浏览到http://localhost:3000/feature_models
,请求成功。
我想说明我的Featuring::FeaturesController
,但我无法找到路线。
以下是规范:
# featuring/spec/controllers/features_controller_spec.rb
require 'spec_helper'
describe Featuring::FeaturesController do
context "feature_models" do
it "GET index should be successful" do
puts Rails.application.routes.routes
get :index, { :use_route => "featuring", :feature => "feature_models" }
response.should be_success
end
end
end
以下是运行此规范的结果:
rspec spec/controllers/features_controller_spec.rb:7
Featuring::FeaturesController
feature_models
GET /feature_models(.:format) {:action=>"index", :controller=>"featuring/features"}
GET /feature_models/:id(.:format) {:action=>"show", :controller=>"featuring/features"}
GET index should be successful (FAILED - 1)
Failures:
1) Featuring::FeaturesController feature_models GET index should be successful
Failure/Error: get :index, { :use_route => "featuring", :feature => "feature_models" }
ActionController::RoutingError:
No route matches {:feature=>"feature_models", :controller=>"featuring/features"}
# ./spec/controllers/features_controller_spec.rb:8:in `block (3 levels) in <top (required)>'
正如您所看到的,即使路线被正确定义,规格控制器似乎也找不到它们。
RoutingError
No route matches {:feature=>"feature_models", :controller=>"featuring/features"}
让我感到惊讶。 action => "index"
未显示。
答案 0 :(得分:0)
我有类似的错误,我也因缺乏{:action =&gt;而感到困惑&#34;索引&#34;}在路线选项中。然而,结果证明这不是问题。 ActionDispatch将缺少的:action视为等同于{:action =&gt; &#34;指数&#34;}。见:
https://github.com/rails/rails/blob/master/actionpack/lib/action_dispatch/routing/route_set.rb#L545
您可能在规范中缺少请求参数,就像我一样。在浏览器中加载页面时,请检查服务器日志中的“参数”行。
答案 1 :(得分:0)
诀窍是将routes { }
添加到您的规范中,如下所示:
describe Featuring::FeaturesController do
routes { Featuring::Engine.routes }
# ...
end