ruby-on-rails - 在 Rails 中使用 RSpec 测试清扫器

标签 ruby-on-rails caching rspec sweeper

我想确保我的清扫器被适本地调用,所以我尝试添加如下内容:

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/

相关文章:

php - 基于超简单静态文件(html)的php站点缓存

c++ - 可以使用缓存制作 QML 应用程序 "offline capable"吗?

ruby-on-rails - 在 Ruby + Rails 中运行 RSPEC

ruby-on-rails - rspec 测试 has_many :through and after_save

ruby-on-rails - Rails 中的 Controller 和 View 中使用的辅助方法

ruby-on-rails - 无法访问 Rails 中的 ENV 变量

首次加载时 jQuery 同位素不起作用,如何等待所有资源/图像加载?

ruby-on-rails - unicorn +NGINX : cannot start unicorn

javascript - 无法加载资源: the server responded with a status of 404 (Not Found) javascript/application. js

ruby-on-rails - RSpec expect 在比较相等的字符串时失败