Friday, October 9, 2009

Catalyst/DBIx::Class and DBD::Mock

I was writing unit tests for a Catalyst-based Perl application today, and, this being my first big application using DBIx::Class, I had no idea how to mock the database layer. I searched the web, to no avail, which leads me to this blog entry: here's how you mock your Catalyst model from a unit test script.

First, you don't have a $c object when you're in a unit test, but it turns out you don't really need it. You also don't need your DB class, which works out nicely. You do, however, need DBD::Mock, as a replacement for your usual DBD package, and, of course, you need to have your result sets in your Perl include path.

Let's say our application is called MyApp, following the convention of the Catalyst documentation.

Now it's easy enough to get a schema object.

my $schema = MyApp::Schema->connect('dbi:Mock:', q{}, q{});

Before you perform any queries, you need to seed that mock DBD with some data. Which means you need access to the DBI object.

my $dbh = $schema->storage->dbh;

Easy, right? Now, let's add some data to the underlying DBD.

my @data =
(
[ qw(column1 column2) ],
[ qw(foo bar) ],
);

$dbh->{mock_add_resultset} = \@data;

This gives the DBD a table with two columns, column1 and column2, and one row containing values "foo" and "bar", respectively.

You're ready to go! Use your schema and result sets as you usually would.

Sunday, October 4, 2009

Things I (Re)discovered Today

I'm in Texas with Helen right now, visiting her family and generally hanging out. It's been a good trip so far, but I had an unusually great number of epiphanies today.


  • I was given the chance to quantify my hatred of racism today, and I discovered that my hatred for it is well and truly deeper than I ever thought it could be.

  • While eating at Love and War in Texas, I was reminded of just how absolutely wonderful food in Texas is. The antelope (antelope! weird!) fillet, venison sausage, and chili were fantastic, but I was also reminded of why I don't like quail too much: all those tiny little bones are very inconvenient.

  • A storm system started pushing through the Dallas area today and will last for another few days. Over many hours of listening to the patter-patter of light rain this evening, I remembered how lovely a rainy day can be.

  • I should get new batteries for my phone and my laptop because they're both lasting about half as long as they originally lasted.

  • Cats, even those that are not my own, seem to like me quite a lot. Helen's mom has two cats, one who is generally stand-offish and another who pretty much just hates people, and they've both decided that I'm a really cool guy with whom they can hang out and purr and have a good time.