I would like to create an Active Record model for Rspec test.
However, this model has callbacks, namely: before_create and after_create method (I think these methods are called callbacks not validation if I am not wrong).
Is there a way to create an object without triggering the callbacks?
Some previous solutions I have tried / does not work for my case:
Update Method:
update_column and other update methods will not work because I would like to create an object and I can't use update methods when the object does not exist.
Factory Girl and After Build:
FactoryGirl.define do
factory :withdrawal_request, class: 'WithdrawalRequest' do
...
after(:build) { WithdrawalRequest.class.skip_callback(:before_create) }
end
end
Failure/Error: after(:build) { WithdrawalRequest.class.skip_callback(:before_create) }
NoMethodError: undefined method `skip_callback' for Class:Class
Skip callbacks on Factory Girl and Rspec
Skip Callback
WithdrawalRequest.skip_callback(:before_create)
withdrawal_request = WithdrawalRequest.create(withdrawal_params)
WithdrawalRequest.set_callback(:before_create)
Failure/Error: WithdrawalRequest.skip_callback(:before_create)
NoMethodError:undefined method `_before_create_callbacks' for #
How to save a model without running callbacks in Rails
I have also tried
WithdrawalRequest.skip_callbacks = true
Which does not work too.
---------- EDIT -----------
My factory function is edited to:
after(:build) { WithdrawalRequest.skip_callback(:create, :before, :before_create) }
My before_create function looks like this:
class WithdrawalRequest < ActiveRecord::Base
...
before_create do
...
end
end
---------- EDIT 2 -----------
I changed the before_create to a function so that I can reference it. Is either of these a better practice?
class WithdrawalRequest < ActiveRecord::Base
before_create :before_create
...
def before_create
...
end
end