【问题标题】:Testing Rails 3.1 engine routes with RSpec 2使用 RSpec 2 测试 Rails 3.1 引擎路由
【发布时间】:2011-09-21 18:47:26
【问题描述】:

我正在尝试使用 RSpec 2 测试 Rails 3.1 引擎。经过大量试验和错误(以及文档和 Stack Overflow 搜索)后,该应用程序正在运行,并且我已经通过了大部分规范。问题是我的路线规格仍然失败。

对于具有隔离命名空间和控制器 Foo::BarsController 的引擎“foo”,我有这个:

require "spec_helper"

describe Foo::BarsController do
  describe "routing" do
    it "routes to #index" do
      get("/foo/bars").should route_to("bars#index")
    end

    it "routes to #new" do
      get("/foo/bars/new").should route_to("bars#new")
    end
  end
end

这会导致:

1) Foo::BarsController routing routes to #index
   Failure/Error: get("/foo/bars").should route_to("bars#index")
   ActionController::RoutingError:
     No route matches "/foo/bars"
   # ./spec/routing/foo/bars_routing_spec.rb:6:in `block (3 levels) in <top (required)>'

2) Foo::BarsController routing routes to #new
   Failure/Error: get("/foo/bars/new").should route_to("bars#new")
   ActionController::RoutingError:
     No route matches "/foo/bars/new"
   # ./spec/routing/foo/bars_routing_spec.rb:10:in `block (3 levels) in <top (required)>'

我的规范虚拟应用程序似乎设置正确:

Rails.application.routes.draw do
  mount Foo::Engine => "/foo"
end

如果有助于回答这个问题,我的视图规范也不起作用。这是一个典型的错误:

9) foo/bars/index.html.erb renders a list of bars
   Failure/Error: render
   ActionView::Template::Error:
     undefined local variable or method `new_bar_path' for #<#<Class:0x00000100c14958>:0x0000010464ceb8>
   # ./app/views/foo/bars/index.html.erb:3:in `___sers_matt__ites_foo_app_views_foo_bars_index_html_erb___1743631507081160226_2184232780'
   # ./spec/views/foo/bars/index.html.erb_spec.rb:12:in `block (2 levels) in <top (required)>'

有什么想法吗?

【问题讨论】:

    标签: ruby-on-rails testing rspec ruby-on-rails-3.1 rails-engines


    【解决方案1】:

    尝试更改您的 get 方法以使用特定路线

    get("/foo/bars", :use_route => :foo)
    

    【讨论】:

    • 这似乎不起作用。 ArgumentError: wrong number of arguments (2 for 1)
    • 我认为混淆是因为get在这种情况下是RSpec的get方法,而上面是Rails方法。
    【解决方案2】:

    好的,我搞定了!并为此写了一篇博文。

    http://www.matthewratzloff.com/blog/2011/09/21/testing-routes-with-rails-3-1-engines/

    它需要一种新方法将引擎路由导入应用程序路由集以进行测试。

    编辑:发现一个命名路由处理的错误并修复它。

    【讨论】:

      【解决方案3】:

      让这个工作实际上并不难。这有点麻烦,因为您要向引擎的 routes.rb 文件添加代码,该文件会根据运行的环境而变化。如果您使用规范/虚拟site approach 来测试引擎,请使用以下代码 sn-p in /config/routes.rb 文件:

      # <your_engine>/config/routes.rb
      
      if Rails.env.test? && Rails.application.class.name.to_s == 'Dummy::Application'
       application = Rails.application
      else
       application = YourEngine::Engine
      end
      
      application.routes.draw do
       ...
      end
      

      这基本上是在为虚拟应用程序切换引擎并在测试模式下将路由写入它。

      【讨论】:

        【解决方案4】:

        【讨论】:

          猜你喜欢
          • 2011-11-19
          • 1970-01-01
          • 2012-05-13
          • 1970-01-01
          • 1970-01-01
          • 2013-06-26
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多