【问题标题】:Rspec controller test fails after using kaminari for pagination使用 kaminari 进行分页后,Rspec 控制器测试失败
【发布时间】:2014-08-27 18:28:16
【问题描述】:

使用 kaminari 进行分页时,我的控制器使用 rspec 测试失败。我的控制器代码和 rspec 测试如下所示。

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

输出:

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

但是,如果我不在控制器中使用分页,它可以工作,下面是不使用分页的代码。

def index
  @courses = Course.all
  authorize! :read, @courses

  respond_to do |format|
    format.html # index.html.erb
    format.json { render json: @courses }
  end
end

您能帮忙解决这个问题吗?提前谢谢你。

【问题讨论】:

  • 你可以试试get :index, :page =&gt; 1..
  • 我已经试过了...没有帮助
  • @ArupRakshit 谢谢你的帮助。下面的回复解决了这个问题。
  • Kaminari.paginate_array(Course.all).page(params[:page]).per(15) 试试这个并告诉我。 Course.all 给你数组,所以这应该工作。

标签: ruby-on-rails ruby rspec pagination kaminari


【解决方案1】:

上面提到的@dax 解决了我在其中一个控制器中选择所有课程的问题,但是在另一个使用嵌套资源的控制器中这不起作用。我关注了@ArupRakshit cmets,它适用于所有场景。

以下是该问题的解决方法。

Kaminari.paginate_array(Course.all).page(params[:page]).per(15)

【讨论】:

    【解决方案2】:

    我认为您应该从以下行中删除 all

    @courses = Course.all.page(params[:page]).per(15)
    

    所以它看起来像这样:

    @courses = Course.page(params[:page]).per(15)
    

    这似乎更符合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)
    

    【讨论】:

    • 我很惊讶这行得通...我尝试传递 :page => 1 和其他东西..但是我从没想过这可以解决问题。
    • 谢谢...我花了很多时间才决定在这里发布问题。非常感谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-10-28
    • 1970-01-01
    • 1970-01-01
    • 2012-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多