2

スイーパーが適切に呼び出されていることを確認したいので、次のようなものを追加してみました。

it "should clear the cache" do
    @foo = Foo.new(@create_params)
    Foo.should_receive(:new).with(@create_params).and_return(@foo)
    FooSweeper.should_receive(:after_save).with(@foo)
    post :create, @create_params
end

しかし、私はただ得ます:

<FooSweeper (class)> expected :after_save with (...) once, but received it 0 times

テスト構成でキャッシュをオンにしようとしましたが、違いはありませんでした。

4

3 に答える 3

3

すでに述べたように、これが機能するには、環境でキャッシュを有効にする必要があります。無効になっている場合、以下の例は失敗します。キャッシング仕様のために、実行時にこれを一時的に有効にすることをお勧めします。

「after_save」はインスタンス メソッドです。クラスメソッドに対する期待を設定したため、失敗しています。

以下は、この期待値を設定するために私が見つけた最良の方法です。

it "should clear the cache" do
  @foo = Foo.new(@create_params)
  Foo.should_receive(:new).with(@create_params).and_return(@foo)

  foo_sweeper = mock('FooSweeper')
  foo_sweeper.stub!(:update)
  foo_sweeper.should_receive(:update).with(:after_save, @foo)

  Foo.instance_variable_set(:@observer_peers, [foo_sweeper])      

  post :create, @create_params
end

問題は、Rails の起動時に Foo のオブザーバー (スイーパーはオブザーバーのサブクラス) が設定されるため、'instance_variable_set' を使用してスイーパー モックをモデルに直接挿入する必要があることです。

于 2009-02-18T14:31:06.217 に答える
2

スイーパーはシングルトンであり、rspec テストの開始時にインスタンス化されます。そのため、MySweeperClass.instance() を介してアクセスできます。これは私にとってはうまくいきました(Rails 3.2):

require 'spec_helper'
describe WidgetSweeper do
  it 'should work on create' do
    user1 = FactoryGirl.create(:user)

    sweeper = WidgetSweeper.instance
    sweeper.should_receive :after_save
    user1.widgets.create thingie: Faker::Lorem.words.join("")
  end
end
于 2012-08-16T03:27:57.747 に答える
2

あなたが持っていると仮定します:

  • FooSweeperクラス_
  • 属性を持つFooクラスbar

foo_sweeper_spec.rb:

require 'spec_helper'
describe FooSweeper do
  describe "expiring the foo cache" do
    let(:foo) { FactoryGirl.create(:foo) }
    let(:sweeper) { FooSweeper.instance }
    it "is expired when a foo is updated" do
      sweeper.should_receive(:after_update)
      foo.update_attribute(:bar, "Test")
    end
  end
end
于 2013-01-22T17:26:16.573 に答える