簡體   English   中英

跳過創建Rails的回調

[英]Skip callback on create Rails

我想為Rspec測試創建一個Active Record模型。

但是,這個模型有回調,即:before_create和after_create方法(我認為如果我沒有錯誤,這些方法被稱為回調而不是驗證)。

有沒有辦法在不觸發回調的情況下創建對象?

以前的一些解決方案我嘗試過/不適合我的情況:

更新方法:

update_column和其他更新方法將無法工作,因為我想創建一個對象,當對象不存在時我不能使用更新方法。

工廠女孩和后建立:

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

失敗/錯誤:在(:build)之后{WithdrawalRequest.class.skip_callback(:before_create)}

NoMethodError:Class:Class的未定義方法`skip_callback'

跳過Factory Girl和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'

如何在不運行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

根據參考答案:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM