[mocha-developer] multiyield

Jay jay at jayfields.com
Fri Sep 29 12:23:31 EDT 2006


I lied, I don't actually need different responses each time I call  
the method.  So the last email of mine is probably worthless.

Instead, I need yield to yield 3 values when I call it once:  
(behavior that mimics Find.find)
   def test_generate(documentation = '/test_documentation/',  
destination = '/destination/')
     Find.expects(:find).with(documentation).multiyield 
('filename.yaml', 'blah.xml')
     File.expects(:directory?).with('filename.yaml')
     File.expects(:directory?).with('blah.xml')
     ....
   end

So, I wrote multiyield....
Index: test/mocha/expectation_test.rb
===================================================================
--- test/mocha/expectation_test.rb      (revision 62)
+++ test/mocha/expectation_test.rb      (working copy)
@@ -91,6 +91,13 @@
      assert_equal parameters_for_yield, yielded_parameters
    end
+  def test_should_yield_multiple_times_with_multiyield
+    expectation = new_expectation.multiyield(:foo, 1, 'bar')
+    actual = []
+    expectation.invoke() { |parameter| actual << parameter }
+    assert_equal [:foo, 1, 'bar'], actual
+  end
+
    def test_should_return_specified_value
      expectation = new_expectation.returns(99)
      assert_equal 99, expectation.invoke
Index: lib/mocha/expectation.rb
===================================================================
--- lib/mocha/expectation.rb    (revision 62)
+++ lib/mocha/expectation.rb    (working copy)
@@ -26,6 +26,10 @@
        @yield = nil
      end

+    def multiyield?
+      @multiyield
+    end
+
      def yield?
        @yield
      end
@@ -178,6 +182,12 @@
        @parameters_to_yield = parameters
        self
      end
+
+    def multiyield(*parameters)
+      @multiyield = true
+      @parameters_to_yield = parameters
+      self
+    end
      # :call-seq: returns(value) -> expectation
      # :call-seq: returns(*values) -> expectation
@@ -218,6 +228,7 @@
      def invoke
        @invoked += 1
        yield(*@parameters_to_yield) if yield? and block_given?
+      @parameters_to_yield.each { |element| yield(element) } if  
multiyield? and block_given?
        @return_value.is_a?(Proc) ? @return_value.call : @return_value
      end

Is this already in the framework and I missed it?


More information about the mocha-developer mailing list