Rails3 RSpec测试routes.rb中的自定义重定向路由

时间:2011-03-17 17:22:21

标签: ruby-on-rails-3 rspec routes

我的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}/ }

做什么是缩短网址并查找实际的网址路径。

但是我的测试失败了:

  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)>'

因此问题在测试级别被隔离。我知道我可以在控制器测试中测试它,但鉴于代码在routes.rb中,我不应该这样做。是否存在使用should route_to在重定向的情况下不起作用的原因?

1 个答案:

答案 0 :(得分:0)

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

在您的路线中执行ActiveRecord查找真的很臭。

如果你必须根据可共享的类型重定向到特定的控制器,那么我将它作为一个带有重定向的单独控制器:

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

然后处理查找记录并从那里重定向到正确的控制器操作:

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

或者......取决于节目动作的相似程度:

class SharableController < ApplicationController

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

end

如果您只处理GET请求,最好更换匹配get:

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