Testing your Mojo with Test::Mojo

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

1 Comment

Hrm, the chaining in the second code segment only makes me think one thing: That's gonna be a massive pain in the neck to run through the debugger when the second test fails. :/

Otherwise it's nice to see such thought put into things.

Leave a comment

About tempire

user-pic I do not like the status quo. There is always a better way; the question is whether you care enough to find it.