Testing with Mechanize

Hello,

I’m trying to jump onto the habit of testing and I’m not finding to too
easy because most of the code I write has to do with third party web
services. My current dilemma is how to stub or mock a Mechanize object
that deals with submitting forms. Can anyone else who tests with
Mechanize please provide some guidance?

Thanks,
Michael B.

On Aug 5, 5:49 pm, Michael B. [email protected] wrote:

Hello,

I’m trying to jump onto the habit of testing and I’m not finding to too
easy because most of the code I write has to do with third party web
services. My current dilemma is how to stub or mock a Mechanize object
that deals with submitting forms. Can anyone else who tests with
Mechanize please provide some guidance?

Maybe try Mechanize::Test, part of the tap-mechanize project:
http://tap.rubyforge.org/tap-mechanize/classes/Tap/Mechanize/Test.html

You may be able to do this with Mocha too. Perhaps someone with more
Mocha experience can chime in.

I think maybe you’re trying to test at the wrong level. Unless you’re
actually testing the behavior of Mechanize, then I would suggest
abstracting
to a higher level.

Wrap your form-submission code in a method, and then mock or stub the
method
out with expected parameters, and perhaps return the contents of an HTML
fixture file.

I know when I go through this sort of exercise, it forces me to think
about
refactoring the code to be more easily testable, which is a nice
side-effect
that usually improves long-term maintainability.

2009/8/5 Michael B. [email protected]

Thanks for the replies Mark and Mike. I never thought about it the way
that you discussed Mike, and I ended up separating the form submission
and page loading code into their own methods, which cleaned up the code
a bit and definitely made it easier for testing. I also started using
Mocha because I like it’s syntax more and find stubbing all instances of
a class to be very useful. I’m glad to say I’ve finally seen the light
of testing :slight_smile: