有没有一种干净的方法来测试Rspec中的ActiveRecord回调?

时间:2012-10-24 14:14:34

标签: ruby activerecord rspec callback

假设我有以下ActiveRecord类:

class ToastMitten < ActiveRecord::Base
  before_save :brush_off_crumbs
end

是否有一种干净的方式来测试:brush_off_crumbs是否已被设置为before_save回调?

“干净”是指:

  1. “没有实际保存”,因为
    • 这很慢
    • 我不需要正确测试ActiveRecord 处理 before_save指令;我需要测试我是否正确告诉它在保存之前该做什么。
  2. “不通过无证方法进行黑客攻击”
  3. 我找到了一种满足标准#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
    

1 个答案:

答案 0 :(得分:9)

使用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会更加尴尬。

相关问题