Rails3 RSpec tests custom route redirection route route.rb

I have a custom redirect on my .rb routes that works fine on 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}/ } 

What happens is to shorten the shortened URL and search for the actual URL.

However, my test does not work:

  it "routes GET 'STU1VWX' to stations/1" do { :get => "STU1VWX" }.should redirect_to( :controller => "stations", :action => "show", :params => {:id => 1} ) end 

WITH

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

Thus, the problem is isolated at the test level. I know that I can verify this in the controller test, but given that the code is in route.rb, I do not need to. Is there a reason why use should route in order not to work in case of redirection?

+4
source share
1 answer

It looks like you are saying here that if you cannot find the page belonging to the hash, redirect to "/"

There's something really smelly about doing ActiveRecord searches on your routes.

If you need to redirect to a specific controller depending on the type of sharing, I would put it as a separate controller with redirection:

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

and then process the record search and redirect to the correct controller action from there:

 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 

OR ... depending on how similar the show actions are:

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

If you deal only with GET requests, it is better to change the match to get the way:

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

Source: https://habr.com/ru/post/1344151/


All Articles