【问题标题】:How to mock method with expectation on what is passed to the block如何模拟方法并期望传递给块的内容
【发布时间】:2010-11-04 21:21:06
【问题描述】:

假设我们有一个类:

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

  def expensive_operation
    #...
  end
end

而且我们已经测试了 cache_handler,所以我们知道它只会在cache 中找不到key 时执行该块。

我们要测试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

【问题讨论】:

    标签: ruby unit-testing mocking rspec


    【解决方案1】:

    这就是我要做的。在同一个对象上模拟另一个方法感觉有点脏(可能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
    

    【讨论】:

    • 听起来很合理。在我看来,在这个例子中存根成本高昂的操作是可以的。
    • 似乎存根缓存总是调用块是要走的路。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多