Reputation: 45
My controller tests using rspec fails while using kaminari for pagination.My Controller code & rspec test are as given below.
app/controllers/courses_controller.rb
def index
@courses = Course.all.page(params[:page]).per(15)
authorize! :read, @courses
respond_to do |format|
format.html # index.html.erb
format.json { render json: @courses }
end
end
spec/controllers/courses_controller.rb
describe "GET index" do
it "assigns all courses as @courses" do
course = create(:course)
get :index, { }
expect(assigns(:courses)).to eq([course])
end
end
OUTPUT:
Failures:
1) CoursesController GET index assigns all courses as @courses
Failure/Error: get :index, { }
ArgumentError:
wrong number of arguments (1 for 0)
# ./app/controllers/courses_controller.rb:5:in `index'
# ./spec/controllers/courses_controller_spec.rb:13:in `block (3 levels) in <top (required)>'
# -e:1:in `<main>'
However if I do not use the pagination in controller it works, below is the code that dont use pagination.
def index
@courses = Course.all
authorize! :read, @courses
respond_to do |format|
format.html # index.html.erb
format.json { render json: @courses }
end
end
Can you help to handle this issue. Thank you in advance.
Upvotes: 0
Views: 1147
Reputation: 45
What @dax mentioned above solved my problem in one of the controller where I was selecting all courses however in another controller where I used nested resources this did not work. I followed @ArupRakshit comments and it works for all scenario.
Below is the fix for the problem.
Kaminari.paginate_array(Course.all).page(params[:page]).per(15)
Upvotes: 1
Reputation: 11007
I think you should remove all
from the following line:
@courses = Course.all.page(params[:page]).per(15)
So it looks like this:
@courses = Course.page(params[:page]).per(15)
This seems to be more in line with the Kaminari documentation:
To fetch the 7th page of users (default per_page is 25)
User.page(7)
To show a lot more users per each page (change the per_page value)
User.page(7).per(50)
Upvotes: 0