路由规范是否支持重定向路由?

在深入研究这个问题后,我对文档的理解和结果之间陷入了僵局。

根据https://www.relishapp.com/rspec/rspec-rails/v/2-8/docs/routing-specs/route-to-matcher ,我们应该能够编写以下内容:

#rspec-rails (2.8.1) #rspec (>= 1.3.1) #rspec-core (~> 2.8.0) # routing spec require "spec_helper" describe BusinessUsersController do describe "routing" do it "routes to some external url" do get("/business_users/7/external_url").should route_to("http://www.google.com") end end end # routes.rb BizeebeeBilling::Application.routes.draw do resources :business_users do member do get "external_url" => redirect("http://www.google.com") end end end 

运行此规范会产生以下结果:失败:

  1) BusinessUsersController routing routes to some external url Failure/Error: assert_routing "/business_users/7/external_url", "http://www.google.com" ActionController::RoutingError: No route matches "/business_users/7/external_url" # ./spec/routing/business_users_routing_spec.rb:19:in `block (3 levels) in ' 

我无法在任何地方找到报告此特定问题的人。

添加细节:手动测试时,路线得到很好的解决。

路由规范/测试专门用于测试路由是否映射到特定控制器和操作(也可能是某些参数)。

我挖了一下Rails和Journey的内部结构。 RSpec和Rails(基本上,遗漏了一些细节)使用Rails.application.routes.recognize_path来回答“这是可路由的吗?”

例如:

 $ rails console
 > Rails.application.routes.recognize_path(“/ business_users / 1”,方法:“GET”)
  => {:action =>“show”,:controller =>“business_users”,:id =>“1”}

但是, /business_users/1/external_url的另一端没有控制器。 事实上,为了执行重定向,Rails创建了一个ActionDispatch::Routing::Redirect实例,它是一个小型的Rack应用程序。 没有触及任何Rails控制器。 您基本上安装了另一个Rack应用程序来执行重定向。

要测试重定向,我建议使用请求规范( spec/requests的文件)。 就像是:

 require "spec_helper" describe "external redirection" do it "redirects to google.com" do get "/business_users/1/external_url" response.should redirect_to("http://www.google.com") end end 

这会隐式测试路由,并允许您测试重定向。

安迪林德曼有正确的答案。 但是,您不必将规范放在规范/请求中,您可以将其保留在规范/路由中并使用元数据“type”显式: describe 'my route', type: :request do

我遇到了类似的情况,我试图测试一系列路线,一些应该重定向,一些不应该。 我想将它们保存在单个路由规范中,因为这是将它们分组的最合理方式。

我尝试使用describe: 'my route', type: request ,但发现不能正常工作。 但是,您可以在规范上下文中包含RSpec::Rails::RequestExampleGroup以访问请求规范方法。 就像是:

 describe "My Routes" do context "Don't Redirect" do it "gets URL that doesn't redirect" do get("business_users/internal_url").should route_to(controller: "business_users", action: "internal_url_action") end end context "Redirection" do include RSpec::Rails::RequestExampleGroup it "redirects to google.com" do get "/business_users/1/external_url" response.should redirect_to("http://www.google.com") end end end 

测试外部重定向的最简单方法是使用集成测试:

  test "GET /my_page redirects Google" do get "/my_page" assert_redirected_to "https://google.com" end 

您需要测试需要位于test/integration目录或集成测试所在的等效目录下。

我想你想要redirect_to匹配器 。