문제

스위퍼가 적절하게 호출되고 있는지 확인하고 싶습니다.

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

테스트 구성에서 캐싱을 켜려고했지만 아무런 차이가 없었습니다.

도움이 되었습니까?

해결책

이미 언급했듯이 캐싱은 환경에서 작동하기 위해 활성화되어야합니다. 비활성화 된 경우 아래의 예제가 실패합니다. 캐싱 사양에 대한 런타임에 일시적으로이를 활성화하는 것이 좋습니다.

'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

문제는 FOO의 관찰자 (스위퍼가 관찰자의 서브 클래스 임)를 부팅 할 때 설정되므로 'instance_variable_set'을 사용하여 스위퍼 모의를 모델에 직접 삽입해야한다는 것입니다.

다른 팁

스위퍼는 싱글 톤이며 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

당신이 가지고 있다고 가정합니다 :

  • FooSweeper 수업
  • Foo a 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
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top