【问题标题】:RSpec test routes with mounted engine安装发动机的 RSpec 测试路线
【发布时间】:2016-01-11 09:39:36
【问题描述】:

我有一个 Rails 应用程序,它将另一个引擎安装到它的路线上,并且还覆盖了引擎中的一些路线。这是routes.rb:

Spree::Core::Engine.routes.draw do
  # some other routes
  root :to => "home#index"
end

MyNamespace::Application.routes.draw do
  class CityConstraint
    def matches?(request)
      Spree::CityZone.where(:url => request.params[:city_name]).exists?
    end
  end
  mount Spree::Core::Engine, :at => ':city_name/', :constraints => CityConstraint.new, :as => :city
  mount Spree::Core::Engine, :at => '/'
end

当我尝试使用 RSpec (2.14) 测试路由时,我总是收到以下错误:

#encoding: utf-8
require 'spec_helper'

RSpec.describe "routes.rb" do
  it "test routing" do
    expect(get: "/").to route_to(controller: "spree/home", action: "index")
  end
end
 Failure/Error: expect(get: "/").to route_to(controller: "home", action: "index")
   No route matches "/"
 # ./spec/routing/routes_spec.rb:6:in `block (2 levels) in <top (required)>'

我发现,当我添加以下行时,它可以工作:

RSpec.describe "routes.rb" do
  routes { Spree::Core::Engine.routes } # this sets the routes
  it "test routing" do
    expect(get: "/").to route_to(controller: "spree/home", action: "index")
  end
end

问题是,我想测试整个应用程序,因为我们在城市名称范围(例如/your_city)和根/ 下安装了两次应用程序。

当我尝试在测试中设置 routes { MyNamespace::Application.routes } 时,我收到 No route matches "/" 错误。

有什么想法可以测试整个安装的路线堆栈,包括来自引擎的路线?

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-3 rspec routing


    【解决方案1】:

    您可以尝试手动添加所需的路线:

    RSpec.describe "routes.rb" do
      before :all do
        engine_routes = Proc.new do
          mount Spree::Core::Engine, 
                :at => ':city_name/', 
                :constraints => CityConstraint.new, 
                :as => :city
          mount Spree::Core::Engine, :at => '/'
        end
        Rails.application.routes.send :eval_block, engine_routes
      end
    
      it "test routing" do
        expect(get: "/").to route_to(controller: "spree/home", action: "index")
      end
    end
    

    想法来自:http://makandracards.com/makandra/18761-rails-3-4-how-to-add-routes-for-specs-only

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-08-04
      • 2015-08-28
      • 2013-03-08
      • 1970-01-01
      • 2011-12-27
      • 2011-11-19
      • 2018-10-01
      • 1970-01-01
      相关资源
      最近更新 更多