2019-05-18 00:54:41 +05:30
|
|
|
# frozen_string_literal: true
|
|
|
|
|
2017-09-10 17:25:29 +05:30
|
|
|
require 'spec_helper'
|
|
|
|
|
|
|
|
describe EachBatch do
|
|
|
|
describe '.each_batch' do
|
|
|
|
let(:model) do
|
|
|
|
Class.new(ActiveRecord::Base) do
|
|
|
|
include EachBatch
|
|
|
|
|
|
|
|
self.table_name = 'users'
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
before do
|
|
|
|
5.times { create(:user, updated_at: 1.day.ago) }
|
|
|
|
end
|
|
|
|
|
2018-12-13 13:39:08 +05:30
|
|
|
shared_examples 'each_batch handling' do |kwargs|
|
|
|
|
it 'yields an ActiveRecord::Relation when a block is given' do
|
|
|
|
model.each_batch(kwargs) do |relation|
|
|
|
|
expect(relation).to be_a_kind_of(ActiveRecord::Relation)
|
|
|
|
end
|
2017-09-10 17:25:29 +05:30
|
|
|
end
|
|
|
|
|
2018-12-13 13:39:08 +05:30
|
|
|
it 'yields a batch index as the second argument' do
|
|
|
|
model.each_batch(kwargs) do |_, index|
|
|
|
|
expect(index).to eq(1)
|
|
|
|
end
|
2017-09-10 17:25:29 +05:30
|
|
|
end
|
|
|
|
|
2018-12-13 13:39:08 +05:30
|
|
|
it 'accepts a custom batch size' do
|
|
|
|
amount = 0
|
2017-09-10 17:25:29 +05:30
|
|
|
|
2018-12-13 13:39:08 +05:30
|
|
|
model.each_batch(kwargs.merge({ of: 1 })) { amount += 1 }
|
2017-09-10 17:25:29 +05:30
|
|
|
|
2018-12-13 13:39:08 +05:30
|
|
|
expect(amount).to eq(5)
|
|
|
|
end
|
2017-09-10 17:25:29 +05:30
|
|
|
|
2018-12-13 13:39:08 +05:30
|
|
|
it 'does not include ORDER BYs in the yielded relations' do
|
|
|
|
model.each_batch do |relation|
|
|
|
|
expect(relation.to_sql).not_to include('ORDER BY')
|
|
|
|
end
|
2017-09-10 17:25:29 +05:30
|
|
|
end
|
|
|
|
|
2018-12-13 13:39:08 +05:30
|
|
|
it 'allows updating of the yielded relations' do
|
|
|
|
time = Time.now
|
2017-09-10 17:25:29 +05:30
|
|
|
|
2018-12-13 13:39:08 +05:30
|
|
|
model.each_batch do |relation|
|
|
|
|
relation.update_all(updated_at: time)
|
|
|
|
end
|
2017-09-10 17:25:29 +05:30
|
|
|
|
2018-12-13 13:39:08 +05:30
|
|
|
expect(model.where(updated_at: time).count).to eq(5)
|
|
|
|
end
|
2017-09-10 17:25:29 +05:30
|
|
|
end
|
2018-12-13 13:39:08 +05:30
|
|
|
|
|
|
|
it_behaves_like 'each_batch handling', {}
|
|
|
|
it_behaves_like 'each_batch handling', { order_hint: :updated_at }
|
2017-09-10 17:25:29 +05:30
|
|
|
end
|
|
|
|
end
|