在创建Rails上跳过回调

时间:2016-06-27 05:26:49

标签: ruby-on-rails callback before-filter

我想为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: 未定义的方法`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'对于#

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

1 个答案:

答案 0 :(得分:4)

根据参考答案:

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