简体   繁体   中英

RSpec test index view and will_paginate

I'm new in test with Ruby and I use Rspec & FactoryGirl for that.

I want to test my index view which obviously has a will_paginate in it.

Here is my controller :

def index
  @products = Product.paginate(:page => params[:page], :per_page=>30)
  respond_with(@products)
end

I have a basic view with will_paginate and a table of products.

Here is my test :

RSpec.describe "products/index", type: :view do
  before(:each) do
    @products = Array.new
    31.times do
      @products << FactoryGirl.create(:product)
    end
    assign(:products, @products)
  end

  it "renders a list of products" do
    render
  end
end

First of all, is it the right way to do it: Create an Array, then assigning it ?

Correct me if I'm wrong but assign(:products, @products) is the equivalent of @products = Product.paginate(:page => params[:page], :per_page=>30) for test ?

I bypassed my issue with this code :

RSpec.describe "products/index", type: :view do
  before(:each) do
    # Create a list of 31 products with FactoryGirl
    assign(:products, create_list(:product, 31))
  end

  it "renders a list of products" do
    allow(view).to receive_messages(:will_paginate => nil)
    render
  end
end

I'm open to any suggestion about this solution.

No, it's not the same. Because an array is different from an ActiveRecord::Relation with Relation methods (this is what Product.paginate(:page => params[:page], :per_page=>30) returns). Maybe is a better way, but this should work:

RSpec.describe "products/index", type: :view do
  before(:each) do
    @products = WillPaginate::Collection.new(4,10,0)
    31.times do
      @products << FactoryGirl.create(:product)
    end
    assign(:products, @products)
  end

  it "renders a list of products" do
    render
  end
end

Here @products = WillPaginate::Collection.new(4,10,0) creates a collection with 4 page and 10 elements on each page.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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