Skip callbacks on Factory Girl and Rspec

前端 未结 16 1021
暗喜
暗喜 2020-12-12 12:17

I\'m testing a model with an after create callback that I\'d like to run only on some occasions while testing. How can I skip/run callbacks from a factory?

c         


        
16条回答
  •  遥遥无期
    2020-12-12 12:58

    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
      end
    end
    

    Running without callback:

    FactoryGirl.create(:user)
    

    Running with callback:

    FactoryGirl.create(:user_with_run_something)
    

提交回复
热议问题