ruby-on-rails - 在 Rails Controller 测试中,有没有办法传递查询(非路由)参数?

标签 ruby-on-rails ruby testing rspec

我正在用 Rails 和 RSpec 编写 Controller 测试,从阅读 ActionController::TestCase 的源代码看来,不可能将任意查询参数传递给 Controller ​​——只能传递路由参数。

为了解决这个限制,我目前正在使用 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 Controller 。这意味着我正在插入一个现有的 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 在路由方面做了一些奇怪的事情。


编辑:

固定在 Devise 中定义路由的位置,并更新我的示例应用以匹配它。

So13866283::Application.routes.draw do
  resource :receive_query_param, :only => [:show],
    :controller => "receive_query_param"
end

...并相应地更新规范和 Controller 以使用#show。测试仍然通过,即 params[:my_param]get :show, :my_param => 'blah' 填充。所以,为什么这不会发生在我的真实应用程序中仍然是个谜。

最佳答案

Controller 测试不路由。您正在对 Controller 进行单元测试——路由超出了它的范围。

一个典型的 Controller 规范示例测试一个 Action :

describe MyController do
  it "is successful" do
    get :index
    response.status.should == 200
  end
end

您通过将参数传递给 get 来设置测试上下文,例如:

  get :show, :id => 1

您可以在该散列中传递查询参数。

如果您确实想要测试路由,您可以编写路由规范或请求(集成)规范。

关于ruby-on-rails - 在 Rails Controller 测试中,有没有办法传递查询(非路由)参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13866283/

相关文章:

ruby-on-rails - 如何删除与数组的任何元素匹配的子字符串

ruby-on-rails - 如何在heroku上使用rails使用twitter/datasift流

ruby - 递归地将 Hash 转换为 OpenStruct

ruby-on-rails - 如何将 RSPEC 配置为从不在 RAILS_ENV 生产环境中运行

ruby-on-rails - ruby 语法(rails 模型)

java - Jersey 容器监听器中事件的集成测试

testing - 错误 : Suite contains no tests

ruby-on-rails - 对 Rails 中正确的 BDD 方法的怀疑

ruby-on-rails - 如何在 Heroku 上分析不一致的 H12 超时

ruby-on-rails - 如何在 Rails 之外使用 Rails 3 的 ActiveSupport 核心扩展