代码之家  ›  专栏  ›  技术社区  ›  mehowte

如何在传递给块的内容上模拟方法

  •  0
  • mehowte  · 技术社区  · 15 年前

    假设我们有一节课:

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

    key 在中找不到 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 回复  |  直到 15 年前
        1
  •  2
  •   trptcolin    15 年前

    这是我要做的。在同一个对象上模拟另一个方法(可能 expensive_operation

    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
    
    推荐文章