我如何通过路由通配符来测试控制器
为了获得调查问卷列表,我使用了
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
并更改参数来测试不同的情况
To get a list of questionnaires I use the
GET "/questionnaires/user/1/public/true/mine/true/shared/true"
in routes.rb I have
/questionnaires/*myparams(.:format) {:controller=>"questionnaires", :action=>"list"}
The controller uses route globbing to create a query in the list method
class QuestionnairesController < ApplicationController
before_filter :authenticate
def list
myparams = params[:myparams].split("/").to_h
end
# ...
end
I am trying to create the test cases for all the options in a spec file
describe "GET list" do
it "returns the list of questionnaires for the user" do
get :list
# ...
end
end
what I get when i run rspec is
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
The question is how do you write the spec file to pass the globbed parameters to rspec. I like to do something like this:
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
and change the parameters to test the different cases
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
通配发生在调度程序中,因此在调用控制器时已经分配了参数。当到达控制器操作时,通配参数应该已经被拆分到
params[:myparams]
中的数组中。如果您想在控制器中测试这一点,只需按照调度程序的方式设置参数哈希:
The globbing happens in the dispatcher, so the params are already assigned when the controller is invoked. When the controller action is reached, the globbed parameters should already be split into an array in
params[:myparams]
.If you want to test this in the controller, just set up the params hash the way the dispatcher would: