ruby-on-rails 创建Rails时跳过回调

js5cn81o  于 2023-06-07  发布在  Ruby
关注(0)|答案(1)|浏览(241)

我想为Rspec测试创建一个活动记录模型。
但是,此模型具有回调,即:before_create和after_create方法(如果我没弄错的话,我认为这些方法被称为回调而不是验证)。
有没有一种方法可以在不触发回调的情况下创建一个对象?
我以前尝试过的一些解决方案/不适用于我的情况:

更新方式:

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

Factory Girl和After Build:

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

失败/错误:after(:build){ WithdrawalRequest.class.skip_callback(:before_create)}
NoMethodError:类的未定义方法“skip_callback”:类
Skip callbacks on Factory Girl and Rspec

跳过回调

WithdrawalRequest.skip_callback(:before_create)

withdrawal_request = WithdrawalRequest.create(withdrawal_params)

WithdrawalRequest.set_callback(:before_create)

失败/错误:withdrawalRequest.skip_callback(:before_create)
NoMethodError:未定义的方法`_before_create_callbacks' for #
How to save a model without running callbacks in Rails
我也试过

WithdrawalRequest.skip_callbacks = true

这也行不通。
---------编辑-----------
我的工厂函数被编辑为:

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

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

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

----------编辑2 -----------
我将before_create改为一个函数,以便可以引用它。这两种做法是否更好?

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

velaa5lx1#

基于参考答案:

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

相关问题