我想确保我的清扫器被适本地调用,所以我尝试添加如下内容:
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 的观察者(清除器是观察者的子类)是在 Rails 启动时设置的,因此我们必须使用“instance_variable_set”将我们的清除器模拟直接插入到模型中。
关于ruby-on-rails - 在 Rails 中使用 RSpec 测试清扫器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/551640/