【发布时间】:2012-10-14 14:28:46
【问题描述】:
假设我有以下 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
【问题讨论】:
标签: ruby activerecord rspec callback