Ruby-on-rails 如何使用rspec测试传递到rails 3中的控制器的参数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8160284/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to test params passed into a controller in rails 3, using rspec?
提问by lkahtz
Our code:
我们的代码:
describe "GET show" do
it "assigns the requested subcategory as @subcategory" do
subcategory = Subcategory.create! valid_attributes
get :show, :id => subcategory.id.to_s
assigns(:subcategory).should eq(subcategory)
end
it "has a sort parameter in the url" do
subcategory = Subcategory.create! valid_attributes
get :show, {:id => subcategory.id.to_s, :params => {:sort => 'title'}}
helper.params[:sort].should_not be_nil
end
end
I got the following error message:
我收到以下错误消息:
1) SubcategoriesController GET show has a sort parameter in the url
Failure/Error: helper.params[:sort].should_not be_nil
NameError:
undefined local variable or method `helper' for #<RSpec::Core::ExampleGroup::Nested_4::Nested_2:0x007f81a467c848>
# ./spec/controllers/subcategories_controller_spec.rb:54:in `block (3 levels) in <top (required)>'
How can I test params in rspec?
如何在 rspec 中测试参数?
回答by jdeseno
get :show, {:id => subcategory.id.to_s, :params => {:sort => 'title'}}
Should be
应该
get :show, :id => subcategory.id.to_s, :sort => 'title'
Unless you mean to pass params[:params][:sort].
除非你想通过params[:params][:sort]。
Also
还
helper.params[:sort].should_not be_nil
Should be
应该
controller.params[:sort].should_not be_nil
controller.params[:sort].should eql 'title'
(If you mean to test a helper, you should write a helper spec.)
(如果你想测试一个 helper,你应该写一个 helper 规范。)
回答by thisismydesign
With Rails 5 the params API changed:
在 Rails 5 中,params API 发生了变化:
get :show, params: { id: subcategory.id.to_s, sort: 'title' }

