【发布时间】:2012-12-13 18:39:58
【问题描述】:
我在 Rails 和 RSpec 中编写控制器测试,从阅读ActionController::TestCase 的源代码看来,不可能将任意查询参数传递给控制器——只能传递路由参数。
为了解决这个限制,我目前使用的是with_routing:
with_routing do |routes|
# this nonsense is necessary because
# Rails controller testing does not
# pass on query params, only routing params
routes.draw do
get '/users/confirmation/:confirmation_token' => 'user_confirmations#show'
root :to => 'root#index'
end
get :show, 'confirmation_token' => CONFIRMATION_TOKEN
end
您可能已经猜到了,我正在为 Devise 测试一个自定义的 Confirmations 控制器。这意味着我正在插入现有的 API,并且无法更改 config/routes.rb 中的实际映射是如何完成的。
有没有更简洁的方法来做到这一点? get 是否支持传递查询参数的方式?
编辑:还有 其他事情正在发生。我在https://github.com/clacke/so_13866283 中创建了一个最小示例:
spec/controllers/receive_query_param_controller_spec.rb
describe ReceiveQueryParamController do
describe '#please' do
it 'receives query param, sets @my_param' do
get :please, :my_param => 'test_value'
assigns(:my_param).should eq 'test_value'
end
end
end
app/controllers/receive_query_param_controller.rb
class ReceiveQueryParamController < ApplicationController
def please
@my_param = params[:my_param]
end
end
config/routes.rb
So13866283::Application.routes.draw do
get '/receive_query_param/please' => 'receive_query_param#please'
end
这个测试通过了,所以我想是 Devise 对路由做了一些时髦的事情。
编辑:
确定设计路线的定义位置,并更新了我的示例应用程序以匹配它。
So13866283::Application.routes.draw do
resource :receive_query_param, :only => [:show],
:controller => "receive_query_param"
end
...并且规格和控制器相应更新以使用#show。测试仍然通过,即params[:my_param] 由get :show, :my_param => 'blah' 填充。所以,为什么在我的真实应用中不会发生这种情况仍然是个谜。
【问题讨论】:
-
和stackoverflow.com/questions/6665743/…不一样——那个是关于路由测试的。但是我会看看我是否可以从中学到一些东西,如果“附加”也可以与
get一起使用。 -
这一行(如果有的话)是关键:github.com/rails/rails/blob/v3.2.8/actionpack/lib/… ...如果我只能找出
query_parameters的定义位置以及如何填充它。 -
链中的下一步是
GET及其别名query_parameters在 github.com/rails/rails/blob/v3.2.8/actionpack/lib/… 中定义并覆盖GET在Rack::Request中。
标签: ruby-on-rails ruby testing rspec