我在
the normal fashion创建了一个Rails引擎,安装了RSpec,并为模型生成了一个脚手架,但我无法通过任何路由规范.
这是一个例子:
describe Licensing::LicensesController do it 'routes to #index' do get('/licensing/licenses').should route_to('licensing/licenses#index') end end
我正在虚拟应用程序中运行示例,如下所示:
$cd spec/dummy $rake spec /Users/brandan/.rvm/rubies/ruby-1.9.3-p194/bin/ruby -S rspec ../routing/licensing/licenses_routing_spec.rb F Failures: 1) Licensing::LicensesController routes to #index Failure/Error: get('/licensing/licenses').should route_to('licensing/licenses#index') No route matches "/licensing/licenses" # /Users/brandan/repos/licensing/spec/routing/licensing/licenses_routing_spec.rb:5:in `block (2 levels) in <top (required)>' Finished in 0.04345 seconds 1 example,1 failure
引擎正确安装在虚拟应用程序中:
# spec/dummy/config/routes.rb Rails.application.routes.draw do mount Licensing::Engine => "/licensing" end
我可以进入虚拟应用程序并启动控制台并获得该路线就好了:
1.9.3p194 :001 > app.get('/licensing/licenses') Licensing::License Load (0.3ms) SELECT "licensing_licenses".* FROM "licensing_licenses" 200 1.9.3p194 :002 > app.response.body "<!DOCTYPE html>..."
虚拟应用程序和RSpec之间存在一些差异,我无法弄清楚它是什么.我找到了几篇声称可以解决这个问题的文章,但是没有一篇文章有帮助,其中有几篇是Rails 3.1特有的:
> Ryan Bigg’s article on generating and testing engines
> Matthew Ratzloff’s article on testing engine routes in Rails 3.1
> Stefan Wienert’s article on mountable engines
> A mailing list message about testing routing helpers in Rails 3.2
有人在Rails 3.2 / RSpec 2.10中解决了这个问题吗?
解决方法
更新(2013-10-31)
RSpec 2.14现在fully supports engine routes:
module MyEngine describe ExampleController do routes { MyEngine::Engine.routes } end end
将其添加到所有路由规范:
# spec/spec_helper.rb config.include Module.new { def self.included(base) base.routes { Reportr::Engine.routes } end },type: :routing
到目前为止我能找到的最佳解决方案是明确设置将在测试期间使用的路由集:
RSpec.configure do |config| config.before(:each,type: :controller) { @routes = Licensing::Engine.routes } config.before(:each,type: :routing) { @routes = Licensing::Engine.routes } end
然后我不得不重写我的路由示例以省略命名空间:
it 'routes to #index' do get('/licenses').should route_to('licensing/licenses#index') end
这似乎有点像黑客,但它确实有道理.我没有测试Rails是否能够在特定路径上安装引擎.我只测试我的引擎是否正确设置了自己的路线.不过,我宁愿不必覆盖实例变量来实现它.
> How to test routes in a Rails 3.1 mountable engine
> How do I write a Rails 3.1 engine controller test in rspec?