rubyfactory-bot

How to have one factory with two different names


We are in the process of migrating our Reply model to a Comment model. In the meantime, I'd like to be able to have :reply and :comment factories that create the same thing.

For example the following code is what I'm using now, but I don't want to "duplicate" the code, I want it to be the exact same factory somehow, or call one from the other.

FactoryBot.define do
  factory :reply do
    sequence(:text) { |n| "Reply #{n}" }
    subject { create(:annotation) if subject_id.nil? && subject_type.nil? }
    user_id { create(:user).id }
  end

  # just mirrors :reply for now, in prep for reply being replaced by comment
  factory :comment, class: 'Reply' do
    sequence(:text) { |n| "Reply #{n}" }
    subject { create(:annotation) if subject_id.nil? && subject_type.nil? }
    user_id { create(:user).id }
  end
end

Solution

  • You can specify aliases for a factory. Docs.

    For Example:

    FactoryBot.define do
      factory :reply, aliases: [:comment] do
        sequence(:text) { |n| "Reply #{n}" }
        subject { create(:annotation) if subject_id.nil? && subject_type.nil? }
        user_id { create(:user).id }
      end
    end