因此,我创建了一个小型模型/ Controller 来使用自定义路由来处理我的应用程序中的 token 。然而,当我运行测试(rspec)时,我会失败
相关代码
Controller
读取 token (在其他地方生成)
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'
rake 路线产生
token_action GET /ta/:uuid(.:format) tokens#read_token {:param=>:uuid}
型号
包含此内容是为了表明创建链接时 token 使用的是 uuid,而不是 id
class Token < ActiveRecord::Base
def to_param
uuid
end
end
并且它在开发模式下工作! :D
但是当我运行测试时......
测试
rspec Controller 测试
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
认为这可能是问题所在 - 我尝试以不同的方式指定属性,但无济于事
- 我尝试了 stackoverflow 上类似问题的所有解决方案
最佳答案
您可以通过添加 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
现在可以使用了;并且仍然使用相同的路径
关于ruby-on-rails - ActionController::UrlGenerationError:没有自定义路由的路由匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34960566/