Created
March 8, 2021 03:50
-
-
Save ReganRyanNZ/71e4128d34459d5b00dcb27d2ba1757e to your computer and use it in GitHub Desktop.
find_or_create for FactoryBot
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# initializers/factory_bot.rb | |
# This needs to be extended in any factory you want its methods in, e.g.: | |
# factory :my_factory do | |
# extend FactoryBotEnhancements | |
# change_factory_to_find_or_create | |
# end | |
# FactoryBot.create(:my_factory) # creates with default attributes | |
# FactoryBot.create(:my_factory) # finds with the same default attributes | |
module FactoryBotEnhancements | |
def change_factory_to_find_or_create | |
# Note that this will ignore nil value attributes, to avoid auto-generated attributes such as id and timestamps | |
to_create do |instance| | |
attributes = instance.class.find_or_create_by(instance.attributes.compact).attributes | |
instance.attributes = attributes.except('id') | |
instance.id = attributes['id'] # id can't be mass-assigned | |
instance.instance_variable_set('@new_record', false) # marks record as persisted | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment