Created
March 25, 2024 12:44
-
-
Save jaydorsey/600cee4090ba9994617320b93d63db4b to your computer and use it in GitHub Desktop.
Add a Trait to skip callbacks in a FactoryBot factory
This file contains hidden or 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
# app/models/user.rb | |
# | |
class User | |
after_create :foo | |
private | |
def foo | |
# ..something we don't do very often | |
end | |
end |
This file contains hidden or 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
# spec/factories/user.rb | |
# | |
# Skips the foo callback generated by each instance where this trait | |
# is called. | |
# | |
# https://stackoverflow.com/a/52107557/2892779 | |
# | |
# Usage: | |
# | |
# create(:user, :skip_foo) | |
FactoryBot.define do | |
factory :user do | |
trait :skip_foo do | |
after(:build) do |member| | |
member.define_singleton_method(:foo) {} | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment