Reputation: 179
I have to test paginate method in my controller.
In my controller
@categories = Category.paginate(:page => params[:page], :per_page => params[:per_page]).all(:order => 'id ASC')
In my spec
Category.should_receive(:paginate)
get :user_category, { :per_page => 1, :page => 1 }
In my log showing
NoMethodError:
undefined method `all' for nil:NilClass
How do I make this test to pass?
Upvotes: 1
Views: 1152
Reputation: 3459
On its own, should_receive
will stub the receiver and cause the method to return nil
.
You can specify a return value, however:
Category.should_receive(:paginate).and_return(categories_mock)
In the later versions of RSpec, you can also set it up to still call and use the return value of the original method:
Category.should_receive(:paginate).and_call_original
Update:
By the way, the all()
call with an argument is no longer supported. You can write the code this way:
@categories = Category.paginate(:page => params[:page], :per_page => params[:per_page]).order('id ASC')
I personally prefer having pagination chained last because it is presentation-related.
For the stubbing, you can use stub_chain()
:
categories_mock = [mock_model(Category)]
Category.stub_chain(:paginate, :order).and_return(categories_mock)
Note that this stubbing can cause problems if you integrate your views, because the pagination helper expects a pagination object and not an array.
Upvotes: 2
Reputation: 1776
I assume you are using the will_paginate
gem.
The paginate helper performs an ActiveRecord query on your database, in your case your test environment database.
The error you get means that no objects were returned by your paginate query.
This is likely due to the fact that your test should look like
Category.should_receive(:paginate)
get :user_category, :per_page => 1, :page => 1
in order to properly set your :per_page
param.
Also, make sure your test db works fine and you actually have some categories in it.
Upvotes: 0
Reputation: 1016
Your test should be:
Category.should_receive(:paginate)
get :user_category, :per_page => 1, :page => 1
In order to have params[:per_page]
Upvotes: 1