【问题标题】:Rails engine: rake routes show its routes but on rspec execution "No route matches" is thrownRails 引擎:rake 路线显示其路线,但在 rspec 执行时抛出“无路线匹配”
【发布时间】:2013-01-18 15:11:14
【问题描述】:

我正在尝试测试我的应用程序正在使用的引擎内部的控制器。规范不在引擎中,而是在应用程序本身中(我尝试在引擎中进行测试,但也遇到了问题)。

我的引擎有以下 routes.rb:

Revision::Engine.routes.draw do
  resources :steps, only: [] do
    collection { get :first }
  end
end

引擎正常挂载在应用routes.rb上:

mount Revision::Engine => "revision"

当我运行rake routes 时,在最后几行我得到:

Routes for Revision::Engine:
first_steps GET /steps/first(.:format) revision/steps#first
       root     /                       revision/steps#first

在我的引擎控制器 (lib/revision/app/controllers/revision/steps_controller.rb) 上,我有:

module Revision
  class StepsController < ApplicationController
    def first
    end
  end
end

在 Rspec 中,我使用以下方法测试此控制器:

require 'spec_helper'
describe Revision::StepsController do
  it "should work" do
    get :first
    response.should be_success
  end
end

然后当我运行这个规范时,我得到:

ActionController::RoutingError:
   No route matches {:controller=>"revision/steps", :action=>"first"}

为确保该路线不存在,我将其添加到规范中:

before do
  puts @routes.set.to_a.map(&:defaults)
end

结果是这样的:

[...]
{:action=>"show", :controller=>"devise/unlocks"}
{:action=>"revision"}

它只有:action 参数。

可能出了什么问题?

【问题讨论】:

    标签: ruby-on-rails ruby unit-testing rspec


    【解决方案1】:

    当您尝试测试引擎的控制器时,您需要指定您希望控制器测试使用的路由集,否则它将针对主应用程序运行它。为此,请将use_route: :engine_name 传递给get 方法。

    require 'spec_helper'
    describe Revision::StepsController do
      it "should work" do
        get :first, use_route: :revision # <- this is how you do it
        response.should be_success
      end
    end
    

    【讨论】:

    • 同意。请注意,仅当 Engine 具有独立的命名空间时才适用。
    • 这帮助我解决了一个甚至与 Rails 引擎无关的问题。我试图访问嵌套在资源内的集合路由,我可以让它识别具有有效路由的操作的唯一方法是传入use_route: :name_of_route。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2017-06-12
    • 2023-03-24
    • 1970-01-01
    • 1970-01-01
    • 2012-10-30
    • 2011-06-14
    • 1970-01-01
    • 2017-11-30
    相关资源
    最近更新 更多