假设我有以下 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
最佳答案
使用run_callbacks
这不那么骇人听闻,但并不完美:
it "is called as a before_save callback" do
revenue_object.should_receive(:record_financial_changes)
revenue_object.run_callbacks(:save) do
# Bail from the saving process, so we'll know that if the method was
# called, it was done before saving
false
end
end
使用这种技术来测试 after_save
会更笨拙。
关于ruby - 有没有一种干净的方法来测试 Rspec 中的 ActiveRecord 回调?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13051082/