7

假设我有以下 ActiveRecord 类:

class ToastMitten < ActiveRecord::Base
  before_save :brush_off_crumbs
end

有没有一种干净的方法来测试:brush_off_crumbs已设置为before_save回调?

“干净”是指:

  1. “没有实际保存”,因为
    • 很慢
    • 我不需要测试 ActiveRecord 是否正确处理指令before_save;我需要测试我是否正确地告诉它在保存之前要做什么。
  2. “无需通过未记录的方法进行黑客攻击”

我找到了一种满足标准#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
4

1 回答 1

11

利用run_callbacks

这不那么hacky,但并不完美:

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

于 2012-10-24T14:31:33.710 回答