gpt4 book ai didi

ruby-on-rails - 路由规范是否支持重定向路由? [RSpec]

转载 作者:行者123 更新时间:2023-12-03 09:00:54 25 4
gpt4 key购买 nike

在对此问题进行了相当深入的研究之后,我陷入了对文档的理解与结果之间的僵局。

根据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 <top (required)>'

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

新增了详细信息:手动测试时,该路径可以很好地解决。

最佳答案

路由规格/测试专门用于测试路由是否映射到特定的 Controller 和 Action (也许还有一些参数)。

我深入研究了Rails和Journey的内部。 RSpec和Rails(基本上省略了一些详细信息)使用Rails.application.routes.recognize_path回答了“这是可路由的吗?”这个问题。

例如:

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

However, there's no controller on the other end of /business_users/1/external_url. In fact, to perform the redirect, Rails has created an instance of ActionDispatch::Routing::Redirect, which is a small Rack application. No Rails controller is ever touched. You're basically mounting another Rack application to perform the redirection.

To test the redirect, I recommend using a request spec instead (a file in spec/requests). Something like:

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

这将隐式测试路由,并允许您针对重定向进行测试。

关于ruby-on-rails - 路由规范是否支持重定向路由? [RSpec],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10842448/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com