Do routing specs support redirect routes? [RSpec]

前端 未结 5 1646
暗喜
暗喜 2021-02-05 02:49

After digging fairly deeply on this issue, I\'ve come to an impasse between my understanding of the documentation and my results.

According to https://www.relishapp.com/

5条回答
  •  不思量自难忘°
    2021-02-05 03:29

    Routing specs/tests specialize in testing whether a route maps to a specific controller and action (and maybe some parameters too).

    I dug into the internals of Rails and Journey a bit. RSpec and Rails (basically, some details left out) use Rails.application.routes.recognize_path to answer the question "is this routable?"

    For example:

    $ 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

    This tests the route implicitly, and allows you to test against the redirection.

提交回复
热议问题