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认为可能是问题您可以通过添加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)
它现在可以工作了;并且仍然使用相同的路径
| 归档时间: |
|
| 查看次数: |
1927 次 |
| 最近记录: |