【问题标题】:how can I rspec test a controller with route globbing我如何 rspec 测试具有路由通配符的控制器
【发布时间】:2023-03-10 18:52:01
【问题描述】:

要获取问卷列表,我使用

GET "/questionnaires/user/1/public/true/mine/true/shared/true"

在 routes.rb 我有

/questionnaires/*myparams(.:format)  {:controller=>"questionnaires", :action=>"list"}

控制器使用路由通配符在列表方法中创建查询

class QuestionnairesController < ApplicationController
  before_filter :authenticate  

  def list  
    myparams = params[:myparams].split("/").to_h
  end

  # ...
end

我正在尝试为规范文件中的所有选项创建测试用例

describe "GET list" do  
  it "returns the list of questionnaires for the user" do  
    get :list  
    # ...  
  end
end

当我运行 rspec 时得到的是

Failures:

1) QuestionnairesController List GET list returns the list of questionnaires for the user
  Failure/Error: get :list
  No route matches {:controller=>"questionnaires", :action=>"list"}
  # ./spec/controllers/questionnaires_controller_spec.rb:20

问题是如何编写规范文件以将全局参数传递给 rspec。我喜欢做这样的事情:

describe "GET list" do 
  it "returns the list of questionnaires for the user" do
    get :list, "/user/1/public/true/mine/true/shared/true"  
  end
end

并更改参数以测试不同的情况

【问题讨论】:

    标签: ruby-on-rails-3 rspec2 glob


    【解决方案1】:

    全局分配发生在调度程序中,因此在调用控制器时已经分配了参数。当到达控制器动作时,全局参数应该已经被拆分为params[:myparams] 中的一个数组。

    如果您想在控制器中进行测试,只需按照调度程序的方式设置参数哈希:

    describe "GET 'list'" do
      it "should be successful" do
        get :list,  :myparams => "user/1/public/true/mine/true/shared/true".split("/")
        response.should be_success
      end
    end
    

    【讨论】:

    • 我最终使用 get :list, :myparams => "rspec/true/user/#{@user.id}/public/true/mine/false/shared/false" 没有拆分,拆分是在控制器内部完成的
    猜你喜欢
    • 1970-01-01
    • 2011-10-06
    • 1970-01-01
    • 2018-02-11
    • 2014-08-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多