ActionController::UrlGenerationError: 自定义路由没有路由匹配

S.K*_*ers 2 ruby routing rspec ruby-on-rails ruby-on-rails-4

所以我创建了一个小模型/控制器来处理我的应用程序中的令牌,带有自定义路由。但是,当我运行测试(rspec)时,我会失败

相关代码

控制器

读取令牌(在别处生成)

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

路线

get '/ta/:uuid' => 'tokens#read_token', param: :uuid, as: 'token_action'
Run Code Online (Sandbox Code Playgroud)

耙路线产生

token_action GET    /ta/:uuid(.:format)    tokens#read_token {:param=>:uuid}
Run Code Online (Sandbox Code Playgroud)

模型

包括以显示令牌在创建链接时使用的是 uuid,而不是 id

class Token < ActiveRecord::Base
  def to_param
    uuid
  end    
end
Run Code Online (Sandbox Code Playgroud)

它在开发模式下工作!: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
Run Code Online (Sandbox Code Playgroud)

错误信息

ActionController::UrlGenerationError: 
    No route matches` {:action=>"read_token", :controller=>"tokens", :uuid=>"12345"}
Run Code Online (Sandbox Code Playgroud)

我试过的

嗯……几乎所有的东西。

  • 我尽我所能写下路线
  • 我改变了:uuid:id认为可能是问题
  • 我尝试以不同的方式指定属性,但无济于事
  • 我在stackoverflow上尝试了所有类似问题的解决方案

S.K*_*ers 5

可以通过添加use_route: :controller_name使其工作来使其工作;

get :index, uuid: "12345", use_route: :tokens
Run Code Online (Sandbox Code Playgroud)

但是我收到这个错误令人困惑和代码异味。

最终解决方案

但是,更好的解决方案是使用正确的 rails 路线资源(http://guides.rubyonrails.org/routing.html

resource :vendor_registration, only: [], path: '/' do
  get :read_token, on: :member, path: '/ta/:uuid'
end
Run Code Online (Sandbox Code Playgroud)

它现在可以工作了;并且仍然使用相同的路径