【问题标题】:How do i use named routes in an Rails engine's specs?如何在铁路引擎规格中使用命名路线?
【发布时间】:2014-11-12 00:29:01
【问题描述】:

我有一个定义了 engine.rb 的 Rails 引擎:

module Keywords
  class Engine < ::Rails::Engine
    isolate_namespace Keywords
end

我定义了一些路线:

Keywords::Engine.routes.draw do
  resources :keyword_groups,  only: [:new] 
end

现在,在我的虚拟应用程序中一切正常。我可以使用变量keywords.new_keyword_group_path 来获取我的路径的url。

但是,当我尝试使用水豚在我的 rspec 测试中做同样的事情时,它失败了!我尝试按照建议将以下行添加到我的 spec_helper.rb 中:

config.include Keywords::Engine.routes.url_helpers

但是,当我尝试在测试中使用以下行时:

visit keywords.new_keyword_group_path

我收到以下错误:

NameError: undefined local variable or method `keywords' for #<RSpec::Core::ExampleGroup::Nested_1:0x00000108833390>

如果我尝试去掉“关键字”前缀,然后这样做:

visit new_keyword_group_path

我得到这个错误:

ActionController::RoutingError: No route matches [GET] "/keyword_groups/new"

这是有道理的,因为路径应该是“/keywords/keyword_groups/new”。

如何让包含的 url 助手使用正确的命名空间前缀?

【问题讨论】:

    标签: ruby-on-rails rspec capybara rails-engines


    【解决方案1】:

    我找到了一个基于 Spree gem 的解决方案。为前缀创建一个辅助方法以从引擎路由中获取路径,如下所示:

    def keywords
      Keywords::Engine.routes.url_helpers
    end
    

    那么keywords.new_keyword_path 就像一个魅力

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-30
      • 2011-12-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多