Forum: Ruby Mocha raise exception first call, return value second call

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
2ebf42f8625b86c0e91ae7bd4e2bef52?d=identicon&s=25 Raymond O'Connor (nappin)
on 2007-03-07 04:23
Is there a way to have mocha raise an exception the first time an stub
is called, and then return a value the second time it is called?

First example, I'm trying to connect to a server and test the case where
my first attempt raises a 'Server busy' exception or something of that
sort.  So I wait, then retry and then the second time the connection is
successful.

Cheers!
Ray
24d2f8804e6bb4b7ea6bd11e0a586470?d=identicon&s=25 Jeremy Kemper (Guest)
on 2007-03-07 05:13
(Received via mailing list)
On 3/6/07, Raymond O'Connor <nappin713@yahoo.com> wrote:
>
> Is there a way to have mocha raise an exception the first time an stub
> is called, and then return a value the second time it is called?
>
> First example, I'm trying to connect to a server and test the case where
> my first attempt raises a 'Server busy' exception or something of that
> sort.  So I wait, then retry and then the second time the connection is
> successful.


server.expects(:connect).returns do
  server.expects(:connect).returns(true)
  raise Busy
end

Hackish? Unclean?  ;-)

jeremy
82a61255b4090da7d3619f870b0794dc?d=identicon&s=25 James Mead (floehopper)
on 2007-03-07 11:04
(Received via mailing list)
On 07/03/07, Raymond O'Connor <nappin713@yahoo.com> wrote:
>
> Is there a way to have mocha raise an exception the first time an stub
> is called, and then return a value the second time it is called?
>
> First example, I'm trying to connect to a server and test the case where
> my first attempt raises a 'Server busy' exception or something of that
> sort.  So I wait, then retry and then the second time the connection is
> successful.


results = [ lambda { raise ServerBusy }, lambda { return true } ]
object.stubs(:connect).returns { lambda { results.shift.call } }

You might be interested in another recent thread (
http://rubyforge.org/pipermail/mocha-developer/200...)
which
discusses how we might come up with a syntax to make this easier.
2ebf42f8625b86c0e91ae7bd4e2bef52?d=identicon&s=25 Raymond O'Connor (nappin)
on 2007-03-08 09:38
Thanks for the help both of you!  I ended up using the method James
proposed (it was cleaner ;) ).

Very interesting thread too.  From a usability standpoint, adding a
raises method to TestCase seems to provide the most intuitive syntax...
at least for me it does.  Can't wait to see how things pan out!
This topic is locked and can not be replied to.