thoughtbot / factory_bot

A library for setting up Ruby objects as test data.
https://thoughtbot.com
MIT License
7.89k stars 2.6k forks source link

Ability to checkpoint and restore sequence state #1631

Open harto opened 3 months ago

harto commented 3 months ago

Problem this feature will solve

Several of our tests rely on sequences being reset between examples. So we call FactoryBot.reload in a before(:each). But this interferes with us being able to use create in a before(:all). For example:

RSpec.describe '…' do
  before(:all) { @user = create(:user) }

  before(:each) { FactoryBot.reload }

  it '…' { another_user = create(:user) }
end

The second call to create will attempt to reuse the same ID from the first call.

Desired solution

It might be good if we could somehow checkpoint the state of the sequences, then restore to that state before each example:

RSpec.describe '…' do
  before(:all) {
    FactoryBot.reload
    @user = create(:user)
    FactoryBot.snapshot
  }

  before(:each) { FactoryBot.rollback }

  # …
end

Alternatives considered

Additional context

We rely on IDs being reset between examples because we use approval tests, and in some cases, object IDs appear in the approval output, and it's not straightforward for us to elide them. So we depend on IDs being generated predictably for each example.