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

これはそれほどハッキーではありませんが、完璧ではありません。

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 に答える