通过Rails中的assert_routing测试具有主机约束的路由
我有一条路线,我使用约束来检查主机,然后是一条本质上相同但没有主机限制的路线(这些实际上是命名空间,但为了简单起见,这个示例将执行此操作):
match "/(:page_key)" => "namespace_one/pages#show", :constraints => proc {|env| env['SERVER_NAME'] == 'test.mysite.local' }
match "/(:page_key)" => "namespace_two/pages#show"
这些工作完全按照预期 进行在定义主机和执行 get "/page_key"
等时通过浏览器和集成测试进行访问。
但是,我想编写测试来确保这些路由到目前为止我没有太多运气以下测试(当前位于 ActionController::IntegrationTest 中,以便我可以设置主机)与没有约束的测试相匹配:
assert_routing '', { :controller => 'namespace_one/pages', :action => 'show' }
=> The recognized options <{"action"=>"show", "controller"=>"frontend/pages"}>
did not match <{"action"=>"show", "controller"=>"namespace_two/pages"}>,
difference: <{"controller"=>"namespace_one/pages"}>
如果我尝试在约束过程中转储环境,我得到的只是 <代码>---:控制器。
如果我摆脱了assert_routing并只执行get :show
调用并转储@controller
它确实解析到正确的控制器(正如预期的那样,这些路由都工作正常)通过 HTTP 请求)。
I have a route which I'm using constraints to check the host and then a route which is essentially the same but without the host restriction (these are really namespaces but to make things simple this example will do):
match "/(:page_key)" => "namespace_one/pages#show", :constraints => proc {|env| env['SERVER_NAME'] == 'test.mysite.local' }
match "/(:page_key)" => "namespace_two/pages#show"
These work exactly as expected when accessing via the browser and in integration tests when defining the host and doing get "/page_key"
etc.
However I want to write tests that ensures that these routes work so far I'm not having much luck as the following test (which is currently in an ActionController::IntegrationTest
so I can set the host) is matching the one without the constraint:
assert_routing '', { :controller => 'namespace_one/pages', :action => 'show' }
=> The recognized options <{"action"=>"show", "controller"=>"frontend/pages"}>
did not match <{"action"=>"show", "controller"=>"namespace_two/pages"}>,
difference: <{"controller"=>"namespace_one/pages"}>
If I try dumping the env in the constraints proc all I get is --- :controller
.
If I get rid of the assert_routing and just do a get :show
call and dump the @controller
it does resolve to the correct controller (as expected as these routes all work fine via HTTP requests).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我自己刚刚遇到这个问题。这个问题已通过 Rails 补丁修复,该补丁允许您在路由测试中指定完整的 url。
将您的测试更改为
,它会正常工作。
你必须在完整的 url 中包含“://”b/crails 使用正则表达式在路径中查找 %r{://},否则它会自动破解 url 的主机部分,并且测试将错误输出。
Just had this problem myself. This was fixed by a Rails patch that allows you to specify full urls in routing tests.
Change your test to
and it will work fine.
You have to include "://" in the full url b/c rails uses a regex to look for %r{://} in the path or it will automatically hack off the host portion of the url, and the test will error out.