使用分页后,规范失败:per_page

时间:2013-12-09 21:52:58

标签: ruby-on-rails-4 railstutorial.org specifications

我正在尝试显示应用程序中的用户列表。为此,我使用了will_paginate gem。但是当我尝试更改页面上显示的用户数量时,尽管应用程序继续正常工作(我认为是这样),但测试仍会下降。

来自 user_pages_spec.rb

的一段代码
describe "pagination" do

  before(:all) { 30.times { FactoryGirl.create(:user) } }
  after(:all)  { User.delete_all }

  it { should have_selector('div.pagination') }

  it "should list each user" do
    User.paginate(page: 1).each do |user|
      expect(page).to have_selector('li', text: user.name)
    end
  end
end

来自 factories.rb

的代码
FactoryGirl.define do
  factory :user do
    sequence(:name) { |n| "Person #{n}" }
    sequence(:email) { |n| "person_#{n}@example.com"}
    password "foobar"
    password_confirmation "foobar"

    factory :admin do
      admin true
    end
  end
end

users_controller.rb

class UsersController < ApplicationController
  before_action :signed_in_user, only: [:index, :edit, :update, :destroy]
  before_action :correct_user,   only: [:edit, :update]
  before_action :admin_user,     only: :destroy

  def index
    #WANT TO CHANGE, DOESN'T WORK
    #@users = User.order('name ASC').paginate(:page => params[:page], :per_page => 8)

    #WORK
    #@users = User.order('name ASC').paginate :page => params[:page]

    #WORK
    #@users = User.paginate(:page => params[:page], :per_page => 30)

    #DOESN'T WORK
    @users = User.paginate(:page => params[:page], :per_page => 8)
  end
...
end

的Gemfile

...
gem 'will_paginate', '3.0.4'
gem 'bootstrap-will_paginate', '0.0.9'
...

命令 bundle exec rspec spec / requests / user_pages_spec.rb

的结果
Failures:

  1) User pages index pagination should list each user
     Failure/Error: expect(page).to have_selector('li', text: user.name)
       expected #has_selector?("li", {:text=>"Person 38"}) to return true, got false
     # ./spec/requests/user_pages_spec.rb:26:in `block (5 levels) in <top (required)>'
     # ./spec/requests/user_pages_spec.rb:25:in `block (4 levels) in <top (required)>'

Finished in 5.51 seconds
32 examples, 1 failure

Failed examples:

rspec ./spec/requests/user_pages_spec.rb:24 # User pages index pagination should list each user

仅适用于 user_pages_spec.rb users_controller.rb 的数字 30 (will_paginate的默认值)。只是这个测试,其他人正在通过。一点帮助都会很好。

1 个答案:

答案 0 :(得分:4)

在rspec spec / requests / user_pages_spec.rb上添加相同的更改

User.paginate(page: 1, :per_page => 8).each do |user|