Skip callbacks on Factory Girl and Rspec

前端 未结 16 1017
暗喜
暗喜 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:59

    Rails 5 - skip_callback raising Argument error when skipping from a FactoryBot factory.

    ArgumentError: After commit callback :whatever_callback has not been defined
    

    There was a change in Rails 5 with how skip_callback handles unrecognized callbacks:

    ActiveSupport::Callbacks#skip_callback now raises an ArgumentError if an unrecognized callback is remove

    When skip_callback is called from the factory, the real callback in the AR model is not yet defined.

    If you've tried everything and pulled your hair out like me, here is your solution (got it from searching FactoryBot issues) (NOTE the raise: false part):

    after(:build) { YourSweetModel.skip_callback(:commit, :after, :whatever_callback, raise: false) }
    

    Feel free to use it with whatever other strategies you prefer.

提交回复
热议问题