Skip callbacks on Factory Girl and Rspec

前端 未结 16 1041
暗喜
暗喜 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 13:08

    FactoryGirl.define do
      factory :order, class: Spree::Order do
    
        trait :without_callbacks do
          after(:build) do |order|
            order.class.skip_callback :save, :before, :update_status!
          end
    
          after(:create) do |order|
            order.class.set_callback :save, :before, :update_status!
          end
        end
      end
    end
    

    Important note you should specify both of them. If only use before and run multiple specs, it'll try to disable callback multiple times. It'll succeed the first time, but on the second, callback isn't going to be defined anymore. So it'll error out

提交回复
热议问题