简体   繁体   English

RSpec控制器分页测试

[英]RSpec Controller Test for Pagination

I'm adding some controller tests to make sure my pagination works correctly. 我正在添加一些控制器测试,以确保我的分页正常工作。 I use the gemfile "Will-paginate", which automatically adds pagination at 30 users. 我使用gem文件“ Will-paginate”,它将自动在30个用户上添加分页。 In this test I add 31 users and look for the selector but the error I'm getting tells me that the pagination never appears. 在此测试中,我添加了31个用户并寻找选择器,但出现的错误告诉我,分页从未出现。 What am I doing wrong? 我究竟做错了什么?

Thanks guys! 多谢你们!

HAML: HAML:

= will_paginate @users, :class => 'pagination'

user_controller_spec.rb user_controller_spec.rb

let(:user) { FactoryGirl.create(:user) }

describe 'GET #index' do
    before { get :index }

    it { should respond_with(200) }
    it { should render_template('index') }
    it { should render_with_layout('application') }
    it { should use_before_action(:authorize_user!) }

    it 'shows pagination' do
      users = FactoryGirl.create_list(:user, 31)
      expect(:index).to have_css('div.pagination')
    end
  end

Error: 错误:

1) Admin::UsersController GET #index shows pagination
 Failure/Error: expect(:index).to have_css('div.pagination')
   expected to find css "div.pagination" but there were no matches

The previous and now deleted answer had it right. 先前的答案(现在已删除)正确了。 You need to create the users before you do the get . get之前,您需要先创建用户。 The problem with both your question and the other answer is the use of let to create users, which lazily evaluates. 您的问题和另一个答案的问题都在于使用let创建用户,该用户懒惰地进行评估。 Try it with let! let!尝试一下let! for defining the users or by putting the creation of users inside a before , as in the following, which also uses subject to keep the setup separate from the code under test. 用于定义用户或将用户的创建放在before ,如下所示,它也使用subject来使设置与受测试的代码分离。

describe 'GET #index' do
    before { FactoryGirl.create(:user, 31) }

    subject { get :index }

    it { should respond_with(200) }
    it { should render_template('index') }
    it { should render_with_layout('application') }
    it { should use_before_action(:authorize_user!) }

    it 'shows pagination' do
      expect(:index).to have_css('div.pagination')
    end
  end
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM