[rspec-users] Simulate an enumerable with a mock

Ashley Moran
Wed, 07 Mar 2007 09:14:50 -0000

I need to simulate an enumerable class (well, it has one method: each).

The code looks something like this OTTOMH:

   class Processor
     def initialize(input, output)
       @input = input; @output = output
     end

     def run
       @input.each do |row|
         @output << ProcessorEngine.new(row).process
       end
     end
   end

This is the best I could come up with:

     @input = mock("input")
     class << @input
       def each
         [ [:a], [:b] ].each do |value|
           yield value
         end
       end
     end

But that seems like adding behaviour to mocks which is generally
recommended against.

There is no way to specify that the each method is called.  I can''t
decide if this would be desirable or not.  What I did instead was
(with the help of a bit more setup)

   ProcessorEngine.should_receive(:new).with([:a]).and_return #blah
   ProcessorEngine.should_receive(:new).with([:b]).and_return #blah

However, the input class is something we made ourselves, and the each
method *is* the interface we defined on it, so I have this nagging
feeling I should test that it is called.

Any thoughts?

Ta
Ashley