Reputation: 3272
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 ?
Upvotes: 2
Views: 1628
Reputation: 53
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.
Upvotes: 1
Reputation: 3272
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.
Upvotes: 2