rom-factory icon indicating copy to clipboard operation
rom-factory copied to clipboard

Allow for creating multiple instances in one DB call

Open apohllo opened this issue 3 years ago • 1 comments

Testing features such as pagination requires presence of a number of objects in the repository. Creation of these entities takes more time, since each faked object is created separately. Yet ROM allows for calling commands with multiple instances, which is much more efficient. It would be a nice feature if instead of

10.times { Factory[:user] }

we had

Factory[:user, instances: 10]

which would be executed as a single DB call.

apohllo avatar Mar 09 '21 10:03 apohllo

This is what I use in these cases

# user_repo.rb
require 'dry/effects'

class UserRepo < ROM::Repository[:users]
  include ::Dry::Effects.Reader(:page_size, default: 20)

  def list(page: 1)
    users.per_page(page_size).page(page).to_a
  end
end

# user_repo_spec.rb
require 'dry/effects'
require 'user_repo'

RSpec.describe UserRepo do
  include Dry::Effects::Handler.Reader(:page_size)
  subject(:repo) { described_class.new }

  describe 'pagination' do
    around { with_page_size(3, &_1) }

    let(:users) { Array.new(4) { Factory[:user] } }

    example 'getting second page' do
      expect(repo.list(page: 2)).to eql(users[3..])
    end
  end
end

flash-gordon avatar Mar 09 '21 20:03 flash-gordon