本文介绍了跳过 Factory Girl 和 Rspec 的回调的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在测试一个带有创建后回调的模型,我只想在测试时在某些情况下运行该回调.如何跳过/运行工厂的回调?
I'm testing a model with an after create callback that I'd like to run only on some occasions while testing. How can I skip/run callbacks from a factory?
class User < ActiveRecord::Base
after_create :run_something
...
end
工厂:
FactoryGirl.define do
factory :user do
first_name "Luiz"
last_name "Branco"
...
# skip callback
factory :with_run_something do
# run callback
end
end
推荐答案
我不确定这是否是最好的解决方案,但我已经成功地实现了这一点:
I'm not sure if it is the best solution, but I have successfully achieved this using:
FactoryGirl.define do
factory :user do
first_name "Luiz"
last_name "Branco"
#...
after(:build) { |user| user.class.skip_callback(:create, :after, :run_something) }
factory :user_with_run_something do
after(:create) { |user| user.send(:run_something) }
end
end
end
无回调运行:
FactoryGirl.create(:user)
使用回调运行:
FactoryGirl.create(:user_with_run_something)
这篇关于跳过 Factory Girl 和 Rspec 的回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!