[rspec-users] how to write spec for infinite loop?

Kero rspec-users at kero.tmfweb.nl
Sun Jun 1 11:30:09 EDT 2008


>> I've got trouble when describe infinite loop.
>>
>> code snippet:
>>
>>  def start_loop
>>    while true
>>      data = self.server.handle_client
>>      if data
>>        self.manager.dispatch(data)
>>      end
>>    end
>>  end
>>
>> without the loop, it is easy to test the logic.
>> but how can I describe it to tell the developer ( me :-) ) that there
>> should be an infinite loop inside.
>
> Here's a tip which Aslak gave me several months ago, and I find myself  
> repeating it in many different contexts on this mailing list:
>
> One way is with dependency injection:
>
> def start_loop(looping_infinitely = true)
>   while looping_infinitely
> 	...
>   end
> end
>
> In your spec, you simply pass false (but production code can call the  
> method as if there is no option).

"while true" is also known as "loop" in Ruby.
Really, you do not want to test whether that ruby construct works, do you?
(I can imagine it being in the test suite that is for RUby itself)

What I think is interesting for you to test, is that your loop keeps running
when the dispatcher dies, and possibly other bad-weather cases. I bet your
loop is in another Thread, and checking whether a Thread still runs is easy
enough (also interesting enough, since threads die by themselves in Ruby,
by default, i.e. they do not raise exceptions in other threads unless you
set Thread.abort_on_exception = true).


More information about the rspec-users mailing list