[Ruby] Forcing exceptions in tests

Tom Lianza tom at lianza.org
Wed Oct 31 10:24:56 PST 2007


On 10/31/07, Laurel Fan <laurel.fan at gmail.com> wrote:
>
> On 10/31/07, Tom Lianza <tom at lianza.org> wrote:
> > I wanted to write some tests such that I can force that exception to
> happen,
> > primarily to ensure that other models which make use of ProductImage
> will
> > gracefully handle errors if they happen from within it.
>
> Sounds like a job for mocks!
>
> Mocha[1] and Flexmock[2] are the two mocking frameworks that I know
> of.  Their feature sets are pretty similar.  They are both much nicer
> than the naive way of making "mock" objects (subclassing and
> overriding) which it sounds like you have come across and do not like.
>
> Check out the mocha/flexmock documentation and examples for details,
> but essentially you do something like:
>
> flexmock(HTTP).should_receive(:get).and_raise(TimeoutError)
>
> and all calls to HTTP::get now return TimeoutError.
>
> [1]: http://mocha.rubyforge.org/
> [2]: http://onestepback.org/software/flexmock/


Thanks Laurel!  I've been considering looking into mocks as a more elegant
way to write tests that depend on web services, but I didn't even think of
the fact that you could use them in this way.  Thanks for the advice.

Tom


More information about the Ruby mailing list