如何测试params传递到rails 3中的控制器,使用rspec?

时间:2011-11-16 23:37:19

标签: ruby-on-rails rspec

我们的代码:

 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

我收到以下错误消息:

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)>'

如何在rspec中测试参数?

2 个答案:

答案 0 :(得分:111)

get :show, {:id => subcategory.id.to_s, :params => {:sort => 'title'}}

应该是

get :show, :id => subcategory.id.to_s, :sort => 'title'

除非您的意思是通过params[:params][:sort]

另外

helper.params[:sort].should_not be_nil

应该是

controller.params[:sort].should_not be_nil
controller.params[:sort].should eql 'title'

(如果您的意思是测试帮助程序,则应编写帮助程序规范。)

答案 1 :(得分:7)

使用Rails 5更改了params API:

get :show, params: { id: subcategory.id.to_s, sort: 'title' }

https://relishapp.com/rspec/rspec-rails/v/3-7/docs/request-specs/request-spec#specify-managing-a-widget-with-rails-integration-methods