Skip callbacks on Factory Girl and Rspec Skip callbacks on Factory Girl and Rspec ruby-on-rails ruby-on-rails

Skip callbacks on Factory Girl and Rspec


I'm not sure if it is the best solution, but I have successfully achieved this using:

FactoryGirl.define do  factory :user do    first_name "Luiz"    last_name "Branco"    #...    after(:build) { |user| user.class.skip_callback(:create, :after, :run_something) }    factory :user_with_run_something do      after(:create) { |user| user.send(:run_something) }    end  endend

Running without callback:

FactoryGirl.create(:user)

Running with callback:

FactoryGirl.create(:user_with_run_something)


When you don't want to run a callback do the following:

User.skip_callback(:create, :after, :run_something)Factory.create(:user)

Be aware that skip_callback will be persistant across other specs after it is run therefore consider something like the following:

before do  User.skip_callback(:create, :after, :run_something)endafter do  User.set_callback(:create, :after, :run_something)end


None of these solutions are good. They deface the class by removing functionality that should be removed from the instance, not from the class.

factory :user do  before(:create){|user| user.define_singleton_method(:send_welcome_email){}}

Instead of suppressing the callback, I am suppressing the functionality of the callback. In a way, I like this approach better because it is more explicit.