ChatGPT解决这个技术问题 Extra ChatGPT

how to test params passed into a controller in rails 3, using rspec?

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?


l
lkahtz
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].

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


Thanks, very helpful. But it needs to add controller in front of params[:sort] to do the trick. Forgive me to take initiative to add two lines to make the spec pass. "controller.params[:sort].should_not be_nil; controller.params[:sort].should eql 'title'"
t
thisismydesign

With Rails 5 the params API changed:

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


Thank you for the update! Can we get this bumped to the accepted answer?