ruby-on-rails-3 - 如何使用路由通配符 rspec 测试 Controller

标签 ruby-on-rails-3 rspec2 glob

要获得问卷 list ,我使用

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

在routes.rb我有
/questionnaires/*myparams(.:format)  {:controller=>"questionnaires", :action=>"list"}

Controller 使用路由通配在列表方法中创建查询
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

问题是你如何编写spec文件来将globbed参数传递给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

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

最佳答案

globbing 发生在调度程序中,因此在调用 Controller 时已经分配了参数。当达到 Controller Action 时,globbed 参数应该已经被拆分成 params[:myparams] 中的一个数组。 .

如果您想在 Controller 中对此进行测试,只需按照调度程序的方式设置 params 散列:

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

关于ruby-on-rails-3 - 如何使用路由通配符 rspec 测试 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5024190/

相关文章:

regex - 通过 Vim 的 Regex 和 globbing 查找重复

python - 将不同子文件夹中具有相同名称的 csv 文件合并为一个 csv

ruby-on-rails - 为什么 ruby​​ 的 '.each' 给出与使用 'for' 不同的结果?

ruby-on-rails-3 - 使用 RSpec 测试嵌套资源 Controller - 计数不会改变 1

ruby-on-rails-3 - $ rspec 规范/不适合我。请帮忙

error-handling - 如何在 Rust 中将 glob::GlobError 转换为 io::Error?

html - rails link_to_add_fields 不使用 has_many :through (with nested form inside) 添加字段

ruby-on-rails - 如何干燥两个不同类中使用的范围方法?

ruby-on-rails - Delayed_Job : accessing job metadata and/or avoiding duplicate jobs

ruby-on-rails - 使用 capybara 时路径无法正常工作