rom-rb / rom-factory

Data generator with support for persistence backends
MIT License
83 stars 42 forks source link

Allow for creating multiple instances in one DB call #65

Open apohllo opened 3 years ago

apohllo commented 3 years ago

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.

flash-gordon commented 3 years ago

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