4

我正在 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"

4

2 回答 2

0

我有一个类似的错误,我也对路由选项中缺少 {:action => "index"} 感到困惑。然而,事实证明这不是问题。ActionDispatch 将缺少 :action 视为等同于 {:action => "index"}。看:

https://github.com/rails/rails/blob/master/actionpack/lib/action_dispatch/routing/route_set.rb#L545

您的规范中可能缺少请求参数,就像我一样。当您在浏览器中加载页面时,检查服务器日志中的参数行。

于 2012-06-08T16:01:18.513 回答
0

诀窍是添加routes { }到您的规范中,如下所示:

describe Featuring::FeaturesController do
  routes { Featuring::Engine.routes }
  # ...
end

另请参阅无路由匹配... Rails 引擎

于 2015-07-11T13:46:28.170 回答