http://www.perlmonks.org?node_id=922639


in reply to Mechanize and Cookie Confusion

One important thing to remember about cookies is ... the host must be sure to send the initial cookie-request to the client, so that the client will have stashed a copy of that cookie and so can return the cookie to you with subsequent requests that it (the client...) makes.   (It is, unfortunately, “annoyingly easy” to set up a cookie in your local database (or “jar”) and to forget to actually send the thing to the client.)   The host must thereafter know that the cookie is there and must not, for example, constantly replace the cookie (a behavior that would imply that the host has amnesia... a very serious host-side bug).

In the case of setting-up Mechanize scripts, of course, the situation is just a little bit different because you are “the client,” but even so, cookies require some care-and-feeding on your part.   There will be some initial request that you issue early on, which you expect (indeed, which you must require) will send back a cookie-value to you.   You need to make sure that the server does not, thereafter, try to replace that cookie with some other value in a way that you know to be wrong.

The “cookie jar” is simply the Mechanize way of capturing the cookies and cookie-values that are involved in the exchange.   Mechanize will handle them in the way that the HTTP protocols prescribe; as any browser also would do in the same situation.   My point is, though, that when you are writing automation scripts, especially testing scripts, you probably need to validate the host’s observed behavior.   But otherwise, no, you don’t have to tell Mechanize when to reach into its jar and grab a chocolate-chip goodie.   When I said, “care and feeding” above, no, I don’t mean that you must intervene in some way to cause Mechanize to Do The Right Thing.™