跳过CREATE RAIRS上的回调



我想为RSPEC测试创建一个活动记录模型。

但是,此模型具有回调,即:fore_create和after_create方法(我认为这些方法称为回调,如果我没有错,则不验证)。

有没有一种方法来创建对象而不触发回调?

我已经尝试过的一些以前的解决方案/对我的情况不起作用:

更新方法:

update_column和其他更新方法将不起作用,因为我想创建一个对象,并且当对象不存在时我无法使用更新方法。

工厂女孩和构建后:

FactoryGirl.define do
  factory :withdrawal_request, class: 'WithdrawalRequest' do
    ...
    after(:build) { WithdrawalRequest.class.skip_callback(:before_create) }
  end
end

失败/错误:after(:build){提取

nomethoderror:未定义的方法`skip_callback'for类:class

跳过对工厂女孩和RSPEC

的回调

跳过回调

WithdrawalRequest.skip_callback(:before_create)
withdrawal_request = WithdrawalRequest.create(withdrawal_params)
WithdrawalRequest.set_callback(:before_create)

失败/错误:提款

nomethoderror:未定义的方法`_before_create_callbacks'for#

如何保存模型而不在Rails中运行回调

我也尝试了

WithdrawalRequest.skip_callbacks = true

也无法正常工作。

-----------编辑-------------

我的工厂功能已编辑为:

after(:build) { WithdrawalRequest.skip_callback(:create, :before, :before_create) }

我的trefor_create函数看起来像这样:

class WithdrawalRequest < ActiveRecord::Base
  ...
  before_create do
    ...
  end
end

-----------编辑2 --------------

我将fortre_create更改为函数,以便我可以参考它。这两个都是更好的做法吗?

class WithdrawalRequest < ActiveRecord::Base
  before_create :before_create
  ...
  def before_create
    ...
  end
end

基于引用答案:

FactoryGirl.define do
  factory :withdrawal_request, class: 'WithdrawalRequest' do
    ...
    after(:build) { WithdrawalRequest.skip_callback(:create, :before, :callback_to_be_skipped) }
   #you were getting the errors here initially because you were calling the method on Class, the superclass of WithdrawalRequest
    #OR
    after(:build) {|withdrawal_request| withdrawal_request.class.skip_callback(:create, :before, :callback_to_be_skipped)}
  end
end

最新更新