[mocha-developer] how to test timeouts? that #returns deprecation again...

Rob Sanheim rsanheim at gmail.com
Wed Sep 5 15:32:38 EDT 2007

I'm writing quite a few specs lately that use Ruby's Timeout::timeout
functionality, making sure that timeout errors are properly handled
and everything flows right when some command line tools timeout.  I
like being able to use Mocha's #returns right now to force a method to
raise a TimeoutError, but I know that usage is going away at some
point.  I'd like to throw out the code and see if anyone has a better
way to test this with Mocha (or otherwise).

Here is some simplified code showing the example:

class FileSpace < ActiveRecord::Base
  def dsmc
   # remove command line wrapper object - this is basically a call
that _could_ stall out

  def self.query_backup_timeout

  # query backup may hang things, so we have to wrap it in a timeout
  def query_backup_from_tsm
    Timeout::timeout(self.class.query_backup_timeout) do

the corresponding spec:

describe "File Space" do
  it "should raise a time out error if query backup takes too long" do
    FileSpace.expects(:query_backup_timeout).returns(0.1) # make
timeout very short
    file_space = FileSpace.new
    # force the parse_query_backup method to sleep for 10 seconds,
therefore making the timeout happen
    file_space.dsmc.expects(:parse_query_backup).returns(lambda{ sleep(10) } )
    e = lambda { file_space.query_backup_from_tsm }.should.raise(Timeout::Error)

Again, this is the simplest case -- in more complex examples I have
specs making sure that the timeout error is logged, and that the error
state gets saved to the database accordingly in the rescue clause.  In
other cases we used modules in our tests to override the real
implementation in the singleton class (by doing
dsmc.extend(TimeoutModule) for example), but thats a bit ugly and

Does anyone see a better way to do this?  I really just want to say "I
don't care what this method normally does, just pretend that in this
spec it takes n seconds long to complete to force a TimeoutError.


More information about the mocha-developer mailing list