简体   繁体   中英

Rspec testing pagination in the controller

I have a controller that gathers data to show on screen like this

@searches.where(user: some_user)
         .between(date1, date2)
         .order("created_at desc")
         .limit(50)
         .offset(params[:pageOffset])

render json: { html: render_to_string(index.html.erb, locals: {searches: @searches}) }

In my controller test, I want to ensure that the limit and the offset work, but I can't do

51.times { FactoryGirl.create(:search) }

Because a search needs to have a user as well as other properties that need to be set to test this properly.

If I were to generate all the data required to get over 50 searches in the database, it would take way too long (I've tried, it's unacceptable)

I need a better solution to test the limit and offset (aka my pagination) in a controller spec. What is a better way that won't slow down the test suite?

I ended up making a design change that primarily helped the tests, but also opened up a future feature possibility. My controller now looks like this:

@searches.where(user: some_user)
     .between(date1, date2)
     .order("created_at desc")
     .limit(params[:page_limit])
     .offset(params[:page_offset])

render json: { html: render_to_string(index.html.erb, locals: {searches: @searches}) }

With my limit being set in the page like this:

var pageLimit = pageLimit || 20;

I can set it or not set it, then when testing I can force it to be small to not overload my tests with factories.

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