thoughtbot / thoughtbot/factory_bot

Configurable ID factory for build_stubbed

Open
#1,605 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

feature
Dominant language
Ruby
Stars
8.2k
Forks
2.6k
PR merge metrics
No merged PRs in 30d

Description

Problem this feature will solve

We use a slightly unconventional ID scheme in our DB. Rather than the usual auto-incrementing IDs or UUIDs, we use string IDs like those found in Stripe's API. (Basically our IDs look like <prefix>_<uuid> where prefix is unique to each model class, but that's not relevant to the request.)

Today, FactoryBot only supports auto-incrementing IDs or UUIDs when building stubbed models.

Desired solution

It would be great if there was a way to provide a callable to FactoryBot to be used to generate IDs for stubbed models. What I had in mind was something like this:

FactoryBot.build_stubbed_id_factory = lambda do |result_instance|
  if funky_model_has_custom_id_generator?(result_instance)
    generate_custom_id(result_instance)
  end

FactoryBot would use the ID factory if it's defined and returns a non-nil result, or fall back to the current behavior otherwise.

Alternatives considered

Right now we're directly patching FactoryBot, but that's obviously not great.

Here's our patch FWIW:

module FactoryBot
  module Strategy
    class Stub
      orig_next_id = instance_method(:next_id)
      define_method(:next_id) do |result_instance|
        if result_instance.class.respond_to?(:generate_id)
          result_instance.class.generate_id
        else
          orig_next_id.bind_call(self, result_instance)
        end
      end
      private :next_id
    end
  end
end

Additional context

I'm happy to submit a PR for this feature if you think it would be a nice addition to the gem.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with FactoryBot::Strategy::Stub#next_id, the entry point shown in the issue's patch, and inspect how build_stubbed currently generates IDs. Define the callable's configuration and fallback behavior, then verify that custom non-nil IDs are used while existing ID generation remains unchanged.

Written by the indexing model from the issue text.

Assessment

Tech stack
ruby
Domain
testing-qa
Issue type
Feature
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.