我有一个定义了 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 测试中使用 capybara 做同样的事情时,它失败了!我尝试按照建议将以下行添加到我的 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 助手使用正确的命名空间前缀?
最佳答案
我找到了一个基于 Spree gem 的解决方案。为前缀创建一个辅助方法以从引擎路由中获取路径,如下所示:
def keywords
Keywords::Engine.routes.url_helpers
end
然后 keywords.new_keyword_path
就像一个魅力
关于ruby-on-rails - 我如何在 Rails 引擎规范中使用命名路由?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26877169/