如何模拟方法,期望传递给块的内容

时间:2010-11-04 21:21:07

标签: ruby unit-testing mocking rspec

让我们说我们有一个班级:

class ObjectWithCaching
  def cached_attribute(key, cache_handler)
    cache_handler.cache(key) { expensive_operation }
  end

  def expensive_operation
    #...
  end
end

我们已经测试了cache_handler,因此我们知道只有在key中找不到cache时才会执行该块。

我们想测试cache_handler #cache是​​否正确执行。

问题是:如何编写剩余的待处理规范?

describe ObjectWithCaching, "#cached_attribute" do
  let(:key) { double }
  let(:cache_handler) { double }

  specify do
    cache_handler.should_receive(:cache).with(key)
    subject.cached_attribute(key, cache_handler)
  end

  it "passes #expensive_operation to block of cache_handler#cache" do
    pending
    subject.cached_attribute(key, cache_handler)
  end
end

1 个答案:

答案 0 :(得分:2)

这就是我要做的。在同一个对象上模拟另一个方法(可能expensive_operation属于另一个类吗?)感觉很脏,但是考虑到约束,我认为这是要走的路。能够直接传递函数并在Clojure中检查函数相等性肯定会很好:)

it "passes #expensive_operation to block of cache_handler#cache" do
  cache_handler.stub!(:cache) do |k, block|
    subject.should_receive(:expensive_operation)
    block.call
  end 

  subject.cached_attribute(key, cache_handler)
end
相关问题