Testing your Jifty apps with fixtures

Testing in web applications always require developers to setup the required records in database to a certain state. One way to do this in Jifty is to maintain a SQLite file as the data set to test with. However this is not good enough since it’s not easily maintainable. If there is a new migration, developers also need to update the SQLite data, which could be a pain in the neck. Other solutions will involve pre-populating the data with Perl, and here’s a very quick sexy way to do it.

In Opmsg, we have a Opmsg::Test::Fixtures that let you do this in your test files:


use Opmsg::Test::Fixtures qw(users messages);

The Perl code of Fixtures module looks like this:


package Opmsg::Test::Fixtures;
use strict;
use warnings;
use utf8;
use encoding 'utf8';
use JiftyX::ModelHelpers;

sub import {
    my ($class, @fixtures) = @_;
    for(@fixtures) {
        if ($class->can($_)) {
            $class->$_();
        } 
    }
}

sub users {
    User->create(name => "user1", openid => "http://user1.example.org");
    User->create(name => "user2", openid => "http://user2.example.org");
    User->create(name => "user3", openid => "http://user3.example.org");
}

sub messages {
    my $u1 = Jifty->app_class("CurrentUser")->new;
    $u1->user_object( User(name => "user1") );
    
    my $m = Message->new(current_user => $u1);
    $m->create(content => "Test Content A");
    $m->create(content => "Test Content B");
    $m->create(content => "測試中文");
} 

1;

Played a little bit import magic here to take arguments from use statement, but not too much.

Using the recently released JiftyX::ModelHelpers module, you’ll find it very readable to write these fixtures. You should be able to easily understand that it’s creating 3 users and 3 messages that belongs to “user1″, even without too much Jifty-fu in your body.

So this is one good way to test your Jifty apps with fixtures.


About this entry