Cold Hard Code

How to test custom Moose types.

I recently had a task where I could either trust my brilliant and prodigious programming skills, or I could write a unit test.

It was really quite easy, and I'm very happy with how easy MooseX::Types makes this.

First, you have to have your types defined, something like this:

Very simple, it just validates the date is after today. Nothing magic. Now, to write a unit test, you have to be able to check this assertion. This is made very easy because MooseX::Types provides an exportable "is_$type" method. However, that doesn't make for easy unit test construction.

Behold, my recipe:

A few things to note that are important:

  • This loudly complains about unimplemented tests
  • This uses some idiomatic Perl, mostly in terms of $code_ref->() — Don't be scared of that.
  • __PACKAGE__->>can("foo") returns an executable code reference, and this recipe shows why that's so useful.

Enjoy.

jshirley

Written by Jay Shirley

Jay Shirley combines technical fundamentals with modern, practical savvy. An open source veteran with plenty of notches in his personal and professional belt, the combination of his work and his field vision (soccer metaphor!) has few rivals.

Comments