6
假設我有以下的ActiveRecord類:是否有一種乾淨的方式來測試Rspec中的ActiveRecord回調?
class ToastMitten < ActiveRecord::Base
before_save :brush_off_crumbs
end
有沒有乾淨的方式來測試:brush_off_crumbs
已被設置爲before_save
回調?
通過 「乾淨」 我的意思是:
- 「沒有實際保存」,因爲
- 它很慢
- 我並不需要測試ActiveRecord的正確處理一個
before_save
指令;我需要測試我是否正確告訴它保存之前要做什麼。
- 「沒有通過無證方法黑客」
我發現滿足條件#1,但不是#2的方式:
it "should call have brush_off_crumbs as a before_save callback" do
# undocumented voodoo
before_save_callbacks = ToastMitten._save_callbacks.select do |callback|
callback.kind.eql?(:before)
end
# vile incantations
before_save_callbacks.map(&:raw_filter).should include(:brush_off_crumbs)
end
這是我見過的最優雅的方式!非常感謝! – rickypai
有沒有像控制器回調的'run_callbacks'? – Dennis
對於'after_save',你可能只需將'should_receive'放在塊內並返回true,即:''revenue_object.run_callbacks(:save)do; revenue_object.should_receive(:record_financial_changes);真正; end' –