Skip callbacks on Factory Girl and Rspec

前端 未结 16 1046
暗喜
暗喜 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条回答
  •  旧时难觅i
    2020-12-12 12:46

    Regarding the answer posted above, https://stackoverflow.com/a/35562805/2001785, you do not need to add the code to the factory. I found it easier to overload the methods in the specs themselves. For example, instead of (in conjunction with the factory code in the cited post)

    let(:user) { FactoryGirl.create(:user) }
    

    I like using (without the cited factory code)

    let(:user) do
      FactoryGirl.build(:user).tap do |u|
          u.define_singleton_method(:send_welcome_email){}
          u.save!
        end
      end
    end
    

    This way you do not need to look at both the factory and the test files to understand the behavior of the test.

提交回复
热议问题