2016-01-23 120 views
2

所以我創建了一個小模型/控制器來處理我的應用中的令牌,並使用自定義路由。然而,當我跑的測試(RSpec的),我會得到一個失敗與ActionController :: UrlGenerationError:自定義路由沒有路由匹配

相關代碼

控制器

讀取令牌(在別處產生)

class TokensController < ApplicationController 
    def read_token 
    #do whatever this token is supposed to do (unsubscribe, confirm email, etc) 
    redirect_to(root_path) 
    end 
end 

路線

get '/ta/:uuid' => 'tokens#read_token', param: :uuid, as: 'token_action' 

耙路線產生

token_action GET /ta/:uuid(.:format) tokens#read_token {:param=>:uuid} 

模式

包括表明創建鏈接時,該令牌使用UUID,而不是ID

class Token < ActiveRecord::Base 
    def to_param 
    uuid 
    end  
end 

和IT開發工作模式! :d

但是,當我跑的測試...

測試

RSpec的控制器測試

require 'rails_helper' 

RSpec.describe TokensController, type: :controller do 
    describe "#index" do 
    it "test" do 
     get :read_token, uuid: "12345" #12345 is obviously not real 
     expect(response).to redirect_to(root_path) 
    end 
    end 
end 

錯誤消息

ActionController::UrlGenerationError: 
    No route matches` {:action=>"read_token", :controller=>"tokens", :uuid=>"12345"} 

我試過

呃...幾乎所有的東西。

  • 我寫的路徑與每一個方法,我可以
  • 我改變:uuid:id以爲可能是問題
  • 我試圖指定的方式不同的屬性,但無濟於事
  • 我想盡解決類似問題上的計算器

回答

4

可以通過添加use_route: :controller_name使這項工作,使其工作;

get :index, uuid: "12345", use_route: :tokens 

但我得到這個錯誤是混亂和代碼味道。

最終解決

然而,更好的解決方案是使用正確的軌道線路資源(http://guides.rubyonrails.org/routing.html

resource :vendor_registration, only: [], path: '/' do 
    get :read_token, on: :member, path: '/ta/:uuid' 
end 

,它現在的作品;並仍然使用相同的路徑

-1
#config/routes.rb 
resources :tokens, path: "token", only: [:create] #-> POST url.com/token 

#app/controllers/tokens_controller.rb 
class TokensController < ApplicationController 
    def create 
     @token = Token.create 
     redirect_to root_url if @token 
    end 
end 

#app/models/token.rb 
class Token < ActiveRecord::Base 
    has_secure_token :uuid 
end 

has_secure_token通過ActiveRecord處理UUID /令牌生成,因此無需通過路由手動設置它(大量的安全優勢)。

-

測試:

require 'rails_helper' 

RSpec.describe TokensController, type: :controller do 
    describe "#create" do 
    it "has_token" do 
     post :create, use_route: :tokens 
     assigns(:token).should_not be_nil 
     expect(response).to redirect_to(root_path) 
    end 
    end 
end 

我不是非常有經驗的測試(今年應該改變);希望你能看到通過後端設置uuid而不是路由的好處。

+0

我認爲這裏有一些困惑。我沒有設置令牌,我正在閱讀它。令牌設置在後端(當前使用'SecureRandom.urlsafe_base64.to_s',但我將查看'has_secure_token') –

+0

:index控制器只讀取令牌。上面的代碼被*非常*減少,以顯示rspec控制器錯誤超過令牌功能 –

+0

好吧,我誤解了你的推理等。仍然不否認你的模式不是那麼好。 –

相關問題