Ruby on rails 3 Rails3 RSpec测试routes.rb中的自定义重定向路由
我在我的routes.rb中有一个自定义重定向,它在ui上运行良好:Ruby on rails 3 Rails3 RSpec测试routes.rb中的自定义重定向路由,ruby-on-rails-3,rspec,routes,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}/ } is所做
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}/ }
is所做的是获取一个缩短的url并查找实际的url路径
然而,我的测试失败了:
it "routes GET 'STU1VWX' to stations/1" do
{ :get => "STU1VWX" }.should redirect_to(
:controller => "stations",
:action => "show",
:params => {:id => 1}
)
end
与:
1)较短的URL重定向路由将“STU1VWX”发送到站点/1
失败/错误:{:get=>“STU1VWX”}。应将_路由到(
ActionController::路由错误:
没有路线匹配“/STU1VWX”
#./spec/routing_spec.rb:12:in'block(2层)in'
因此,问题是在测试级别隔离的。我知道我可以在控制器测试中测试这一点,但考虑到代码在routes.rb中,我不应该这样做。在重定向的情况下,使用should route_不起作用有其内在的原因吗?看起来你在这里说,如果你找不到属于散列的页面,那么重定向到“/” 在您的路由中执行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
您是否尝试了
match'/:hash'
而不是match':hash'
?您不应该在路由中执行ActiveRecord查询…我相信这是因为您无法在路由规范中测试重定向。您将需要使用请求规范测试重定向。这已作为问题提交给rspec rails,但已关闭:。
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 "/:hash" => 'SharableController#redirect', :constraints => { :hash => /[a-zA-Z0-9]{7}/ }