Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
branch: master
Fetching contributors…

Octocat-spinner-32-eaf2f5

Cannot retrieve contributors at this time

file 52 lines (46 sloc) 1.494 kb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
require 'active_record'
require 'minitest/autorun'
require 'minitest/spec'
require 'logger'
require_relative '../lib/ar-as-batches'
require_relative './test_helper'

describe ActiveRecord::Relation do
  describe "#as_batches" do
    before do
      # to verify the SQL we're generating
      @out=StringIO.new
      l=Logger.new(@out)
      l.formatter=Logger::Formatter.new
      ActiveRecord::Base.logger=l
      @ds=TestRecord.where("number < 500")
    end
    def queries
      @out.string.split(/\n/).map {|l| m=l.match(/(SELECT .*)$/) and m[0] }
    end

    it "produces queries with offsets 0,200,400 when called with batch size 200 and a query producing 500 rows" do
      count=0
      @ds.as_batches(:batch_size=>200) do |r|
        count+=1
      end
      assert_equal 500,count
      q=queries
      assert_equal 4,q.count
      [0,200,400,500].each_with_index do |offset,i|
        assert_match /LIMIT 200 OFFSET #{offset}/,q[i]
      end
    end

    it "produces queries with offsets 50,250,450 when given non-zero offsets" do
      @ds.offset(50).as_batches(:batch_size=>200) { |r| true }
      q=queries
      [50,250,450,500].each_with_index do |offset,i|
        assert_match /LIMIT 200 OFFSET #{offset}/,q[i]
      end
    end

    it "stops early when a limit is given" do
      @ds.limit(300).as_batches(:batch_size=>200) { |r| true }
      q=queries
      assert_match /LIMIT 200 OFFSET 0/,q[0]
      assert_match /LIMIT 100 OFFSET 200/,q[1]
    end

  end
end
Something went wrong with that request. Please try again.