Add find_or_create_by Method

Author: hatsu38Created Jul 20, 2024Updated Mar 12, 2026
Labelsfeature

Problem this feature will solve

When setting up test data with FactoryBot, it can be cumbersome and repetitive to check if a record exists before creating it. For instance, in our current test setup, we have to manually use find_by followed by create if the record is not found.

ruby
RSpec.describe User do 
  before(:all) { Fixtures.setup_basics }
  
  it do
    # aa
  end
  
  it do
    # aa
  end
end


module Fixtures
  def self.setup_basics
    setup_normal_plan
    setup_high_plan
  end

  def self.normal_plan
      a_token = FactoryBot.create(:token :free)
      b_token = FactoryBot.create(:token, :normal)
     # etc...
  end

  def self.high_plan
    a_token = Token.find_by(name: "free") || FactoryBot.create(:token :free)
    b_token = Token.find_by(name: "normal") || FactoryBot.create(:token :normal)
  end
end

Desired solution

ruby
  def self.high_plan
    a_token = Token.find_or_create_by(:token :free)
    b_token = Token.find_or_create_by(:token :normal)
  end

Alternatives considered

ruby
  def self.high_plan
    a_token = Token.find_by(name: "free") || FactoryBot.create(:token :free)
    b_token = Token.find_by(name: "normal") || FactoryBot.create(:token :normal)
  end

Additional context