# Mocha test retry to connect up to 10 times

**URL:** <https://www.ruby-forum.com/t/mocha-test-retry-to-connect-up-to-10-times/86554>\
**Category:** Ruby\
**Created:** [February 23, 2007, 6:57am UTC](https://www.ruby-forum.com/t/mocha-test-retry-to-connect-up-to-10-times/86554 "2007-02-23T06:57:28Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![nappin](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/n/f475e1/32.png) [@nappin](https://www.ruby-forum.com/u/nappin)\
**Post date:** [February 23, 2007, 6:57am UTC](https://www.ruby-forum.com/t/mocha-test-retry-to-connect-up-to-10-times/86554/1 "2007-02-23T06:57:28Z")

</div>

I’m writing a script to connect to an external server. The problem is  
that the server can be flaky and respond with an error code on some  
requests. When the response I get is an error I would like to retry  
connecting. If I retry 10 times and fail to connect, I just abort.

With mocha I can test the case where each of the 10 attempts receives an  
error code, but I can’t figure out a way to stub HTTP so that it will  
return an error only 1 or 2 times, and then return a success. Anyone  
know a good way to test receiving an error a few times and then  
receiving a success?

Any help would be greatly appreciated, thanks!

---

<div class="post-metadata">

**Author:** ![nappin](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/n/f475e1/32.png) [@nappin](https://www.ruby-forum.com/u/nappin)\
**Post date:** [February 23, 2007, 7:31am UTC](https://www.ruby-forum.com/t/mocha-test-retry-to-connect-up-to-10-times/86554/2 "2007-02-23T07:31:39Z")

</div>

On Fri, 2007-02-23 at 14:57 +0900, Raymond O’connor wrote:

> Any help would be greatly appreciated, thanks!

With latest version of Mocha, you can actually do something like this:

TCPSocket.stubs(:open).returns(data1,data2,data3)

where first call would return data1, second call data2 so on and so  
forth. I hope, you can use this to your advantage.

---

<div class="post-metadata">

**Author:** ![nappin](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/n/f475e1/32.png) [@nappin](https://www.ruby-forum.com/u/nappin)\
**Post date:** [February 23, 2007, 9:20am UTC](https://www.ruby-forum.com/t/mocha-test-retry-to-connect-up-to-10-times/86554/3 "2007-02-23T09:20:32Z")

</div>

Hemant K. wrote:

> On Fri, 2007-02-23 at 14:57 +0900, Raymond O’connor wrote:
> 
> > Any help would be greatly appreciated, thanks!
> 
> With latest version of Mocha, you can actually do something like this:
> 
> TCPSocket.stubs(:open).returns(data1,data2,data3)
> 
> where first call would return data1, second call data2 so on and so  
> forth. I hope, you can use this to your advantage.

That worked perfectly! Thanks a ton!
