加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 在Rails Controller测试中,有没有办法传递查询

发布时间:2020-12-17 02:37:43 所属栏目:百科 来源:网络整理
导读:我正在Rails和RSpec中编写控制器测试,从阅读ActionController :: TestCase的源代码看,它不可能将任意查询参数传递给控制器?? – 只有路由参数. 要解决此限制,我目前正在使用with_routing: with_routing do |routes| # this nonsense is necessary because #
我正在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中实际映射的完成方式.

有没有更简洁的方法来做到这一点?获取传递查询参数的支持方式?

编辑:还有其他事情发生.我在https://github.com/clacke/so_13866283中创建了一个最小的例子:

规格/控制器/ 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

应用程序/控制器/ receive_query_param_controller.rb

class ReceiveQueryParamController < ApplicationController
  def please
    @my_param = params[:my_param]
  end
end

配置/ 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

…并且相应地更新规范和控制器以使用#show.测试仍然通过,即para:[:my_param]由get:show,:my_param =>填充. “胡说”.所以,仍然是一个谜,为什么这不会发生在我的真实应用程序中.

解决方法

控制器测试不会路由.您正在对控制器进行单元测试 – 路由超出了其范围.

典型的控制器规范示例测试一个动作:

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

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

get :show,:id => 1

您可以在该哈希中传递查询参数.

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读