gpt4 book ai didi

ruby-on-rails-3 - Rails3 RSpec 在 routes.rb 中测试自定义重定向路由

转载 作者:行者123 更新时间:2023-12-01 06:45:57 27 4
gpt4 key购买 nike

我的 routes.rb 中有一个自定义重定向,它在 ui 上工作正常:

match ':hash' => redirect { |params| begin url = Sharing.find_by_short_url(params[:hash]); "/#{url.shareable_type}/#{url.shareable_id}/" rescue '/' end }, :constraints => { :hash => /[a-zA-Z0-9]{7}/ }

它的作用是获取一个缩短的 url 并查找实际的 url 路径。

但是我的测试失败了:
  it "routes GET 'STU1VWX' to stations/1" do
{ :get => "STU1VWX" }.should redirect_to(
:controller => "stations",
:action => "show",
:params => {:id => 1}
)
end

和:
  1) Shorter URL redirect routes GET 'STU1VWX' to stations/1
Failure/Error: { :get => "STU1VWX" }.should route_to(
ActionController::RoutingError:
No route matches "/STU1VWX"
# ./spec/routing_spec.rb:12:in `block (2 levels) in <top (required)>'

所以问题是在测试级别隔离的。我知道我可以在 Controller 测试中对此进行测试,但鉴于代码在 routes.rb 中,我不应该这样做。在重定向的情况下,使用 should route_to 是否存在固有的原因?

最佳答案

看起来你在这里说如果你找不到属于哈希的页面,那么重定向到“/”

在您的 route 执行 ActiveRecord 查找真的很糟糕。

如果您必须根据可共享类型重定向到特定 Controller ,那么我会将其作为带有重定向的单独 Controller :

match "/:hash" => 'SharableController#redirect':constraints => { :hash => /[a-zA-Z0-9]{7}/ }

然后处理查找记录并从那里重定向到正确的 Controller 操作:
class SharableController < ApplicationController

def redirect
@sharable = Sharable.find_by_sharable_type(params[:hash])
redirect_to controller: @sharable.sharable_type, action: 'show', id: @sharable.id
end

end

或...取决于表演 Action 的相似程度:
class SharableController < ApplicationController

def redirect
@sharable = Sharable.find_by_sharable_type(params[:hash])
render template: "#{@sharable.sharable_type.pluralize}/show"
end

end

如果您只处理 GET 请求,最好将 match 换成 get 顺便说一下:
get "/:hash" => 'SharableController#redirect', :constraints => { :hash => /[a-zA-Z0-9]{7}/ }

关于ruby-on-rails-3 - Rails3 RSpec 在 routes.rb 中测试自定义重定向路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5342761/

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