未定义的方法total_pages'对于数组will_paginate rspec

时间:2015-02-06 15:17:26

标签: ruby-on-rails ruby ruby-on-rails-4 rspec

我已将gem'will_paginate'和gem'will_paginate-bootstrap'添加到我的应用中,它运行正常。但是由于RSpec测试,我确实收到了此错误消息。

Failure/Error: render
     ActionView::Template::Error:
       undefined method `total_pages' for #<User::ActiveRecord_Relation:0x007f8c238a97b8>

这是Rspec代码:

 it "renders a list of users" do
    render

    page = Capybara::Node::Simple.new(rendered)

    expect(page).to have_content("Smith, Agent admin@somewhere.com Site Admin")
    expect(page).to have_content("Johnson, Bob manager.email@elsewhere.com The Company Name")
  end

users_controller.rb

def index
    @per_page = params[:per_page] || 10
    @users = User.paginate(:page => params[:page], :per_page => @per_page).order('last_name  ASC')
end

index.html.erb

<div class="pull-right">
  Records per page
  <%= select_tag :per_page, options_for_select([10,25,50,100], params[:per_page].to_i),
       :onchange => "if(this.value){window.location='?per_page='+this.value;}" %>
</div>

<%= page_entries_info @users %>

<br>
<div class="pull-right">
  <%= will_paginate @users, renderer: BootstrapPagination::Rails %>
</div>

2 个答案:

答案 0 :(得分:5)

如果您使用的是Rspec&gt; = 3,请尝试以下操作:

 it "renders a list of users" do
    allow(view).to receive_messages(:will_paginate => nil) # Add this

    render

    page = Capybara::Node::Simple.new(rendered)

    expect(page).to have_content("Smith, Agent admin@somewhere.com Site Admin")
    expect(page).to have_content("Johnson, Bob manager.email@elsewhere.com The Company Name")
  end

答案 1 :(得分:0)

使用Kaminari助手


RSpec.describe 'rendering view', type: :view do

  let(:posts) do
    Kaminari.paginate_array(create_list(:post, 10)).page(1)
  end

  it 'displays posts' do
    # assign(:posts, posts) # if it's instance variable
    render partial: '/post_list.html.erb', :locals => {:posts => posts }
  end

end