假设我有以下 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