February 9, 2011

Testing your Mojo with Test::Mojo

Update Mojo::Client has been replaced with Mojo::UserAgent.

They say programmers don't like to test.

It seems to me that the folks who say that aren't programmers. If they are, they've never been the sole responsible party for any application. When there's no one to pass the blame to, TDD is no longer just an idea, it's time & money.

Once you get the hang of it, the peace of knowing that your code works has a value beyond measurement.

It's for this reason Mojolicious makes it easy to test your web apps in a clean, simple manner.

Now that's easy. But there's more.

Test::Mojo tests are chainable, so you can keep your tests in a clean group:

Now that's pretty. But wait, there's more.

Using Mojolicious' built in JSON parser, you can test JSON output using an equivalent decoded Perl structure:

On a side note, Mojo::JSON is the fastest pure-perl JSON parser available. Thanks to chansen, it recently became even faster, outperforming JSON::PP by 3x.

But wait, there's more.

Test::Mojo methods have exactly the same syntax as their corresponding Mojo::Client methods, sharing much of the same code.

For example, with Mojo::Client, you would write:

Testing the route would be nearly the same thing - Just add the _ok suffix, and you're good to go:

As a matter of fact, testing with all the HTTP methods have the same naming scheme:

But wait, there's more.

Much like Mojo::Client, Test::Mojo automatically stores cookies for you, so you can test cookie-based web apps without any extra code.

When you need to drop existing cookies, you can reset the session:

Sometimes, it's necessary to break free and do your own thing. You can access the most recent transaction using the ->tx accessor:

Installing is one-step easy, and takes about a minute:

curl -L cpanmin.us | perl - Mojolicious

One more thing...

Since Test::Mojo is based Mojo::Client, you can debug your tests by printing the HTTP request/response to stderr using an environment variable:

MOJO_CLIENT_DEBUG=1 prove t/webapp.t

You've got the idea. Now go test your web apps!

Test::Mojo docs

comments powered by Disqus