Allow defining the starting id for build_stubbed

Some codebases have long builds that create over 1000 records, and may
have id collisions between records created with FactoryBot.create and
FactoryBot.build_stubbed

Co-authored-by: Daniel Colson <danieljamescolson@gmail.com>
This commit is contained in:
Victor Mours 2020-04-26 15:33:43 -04:00 committed by Daniel Colson
parent 9919863184
commit 65e64ec2a3
No known key found for this signature in database
GPG Key ID: 88A364BBE77B1353
3 changed files with 31 additions and 0 deletions

View File

@ -66,6 +66,15 @@ module FactoryBot
Linter.new(factories_to_lint, **options).lint!
end
# Set the starting value for ids when using the build_stubbed strategy
#
# Arguments:
# * starting_id +Integer+
# The new starting id value.
def self.build_stubbed_starting_id=(starting_id)
Strategy::Stub.next_id = starting_id - 1
end
class << self
delegate :callback_names,
:callbacks,

View File

@ -24,6 +24,10 @@ module FactoryBot
:update_columns,
].freeze
def self.next_id=(id)
@@next_id = id
end
def association(runner)
runner.run(:build_stubbed)
end

View File

@ -279,3 +279,21 @@ describe "defaulting `id`" do
expect(FactoryBot.build_stubbed(:post, id: 12).id).to eq 12
end
end
describe "configuring the starting id" do
it "defines which id build_stubbed instances start with" do
define_model("Post")
FactoryBot.define do
factory :post
end
FactoryBot.build_stubbed_starting_id = 1000
expect(FactoryBot.build_stubbed(:post).id).to eq 1000
FactoryBot.build_stubbed_starting_id = 3000
expect(FactoryBot.build_stubbed(:post).id).to eq 3000
end
end