Home > database >  Use of Pagy rubygem in Rails tests with MiniTest
Use of Pagy rubygem in Rails tests with MiniTest

Time:07-04

I have a Rails app that I have upgraded from Rails 6 to 7 app. In previous version I was using will_paginate gem (v. 3.3.1) and Bootstrap 3. Now I have decided to switch to pagy (v. 5.10.1). I have followed the migration guide and made necessary changes. I have run the local server and everything is working fine. However I am having problems with testing of pagination in my integration tests. I have tried writing the code as shown in the API documentation but I keep getting errors. I would appreciate any advice or guidance on this as I am fairly new learner of Rails and am having hard time figuring out why it is not working in test environment while everything in development is fine. Thanks to everyone in advance for the time and help, I really appreciate the community here.

Below are extracts from my tests and controllers, where I have omitted some parts for brevity.

user_following_test.rb

 test 'feed on Home page' do
    get root_path
    @pagy, @user = pagy(@user.feed, page: 1).each do |micropost|
      assert_match CGI.escapeHTML(micropost.content), response.body
    end
  end
  # Previous code that worked with will_paginate
  # test 'feed on Home page' do
  #   get root_path
  #   @user.feed.paginate(page: 1).each do |micropost|
  #     assert_match CGI.escapeHTML(micropost.content), response.body
  #   end
  # end
end

users_controller.rb

class UsersController < ApplicationController
  ...
  def index
    @pagy, @users = pagy(User.where(activated: true))
  end

  def show
    @user = User.find(params[:id])
    @pagy, @microposts = pagy(@user.microposts)
    redirect_to(root_url) unless @user.activated?
  end

My intention to check that show method in users controller is working as intended. Result of running the test is a very long stack trace that ends with:

Did you mean?  pagy_t
            test/integration/following_test.rb:60:in `block in <class:FollowingTest>'

CodePudding user response:

The pagy method is in the default configuration only available on the controller level, but not globally. You need to include Pagy::Backend to have it available in other classes.

I reckon the following might work:

include Pagy::Backend

test 'feed on Home page' do
  get root_path

  _pagy, microposts = pagy(@user.feed, page: 1)

  microposts.each do |micropost|
    assert_match CGI.escapeHTML(micropost.content), response.body
  end
end
  • Related