DBICx::TestDatabase - create a temporary database from a DBIx::Class::Schema


DBICx-TestDatabase documentation Contained in the DBICx-TestDatabase distribution.

Index


Code Index:

NAME

Top

DBICx::TestDatabase - create a temporary database from a DBIx::Class::Schema

SYNOPSIS

Top

Given a DBIx::Class::Schema at MyApp::Schema, create a test database like this:

   use DBICx::TestDatabase;
   my $schema = DBICx::TestDatabase->new('MyApp::Schema');

Then you can use $schema normally:

   $schema->resultset('Blah')->create({ blah => '123' });

When your program exits, the temporary database will go away.

DESCRIPTION

Top

This module creates a temporary SQLite database, deploys your DBIC schema, and then connects to it. This lets you easily test your DBIC schema. Since you have a fresh database for every test, you don't have to worry about cleaning up after your tests, ordering of tests affecting failure, etc.

METHODS

Top

new($schema)

Loads $schema and returns a connection to it.

connect

Alias for new.

ENVIRONMENT

Top

You can control the behavior of this module at runtime by setting environment variables.

DBIC_KEEP_TEST

If this variable is true, then the test database will not be deleted at END time. Instead, a message containing the paths of the test databases will be printed.

This is good if you want to look at the database your test generated, for debugging.

(Note that the database will never exist on disk if you don't set this to a true value.)

AUTHOR

Top

Jonathan Rockway <jrockway@cpan.org>

LICENSE

Top

Copyright (c) 2007 Jonathan Rockway.

This program is free software. You may use, modify, and redistribute it under the same terms as Perl itself.


DBICx-TestDatabase documentation Contained in the DBICx-TestDatabase distribution.

package DBICx::TestDatabase;
use strict;
use warnings;

use File::Temp 'tempfile';

our $VERSION = '0.04';

# avoid contaminating the schema with the tempfile
my @TMPFILES;

sub new {
    my ($class, $schema_class) = @_;

    eval "require $schema_class"
      or die "failed to require $schema_class: $@";

    my $filename = ':memory:'; # use in-memory database

    if($ENV{DBIC_KEEP_TEST}){
        (undef, $filename) = tempfile;
        push @TMPFILES, $filename;
    }

    my $schema = $schema_class->connect( "DBI:SQLite:$filename", '', '',
        { sqlite_unicode => 1 } )
        or die "failed to connect to DBI:SQLite:$filename ($schema_class)";

    $schema->deploy;
    return $schema;
}

END {
    if($ENV{DBIC_KEEP_TEST}){
        print {*STDERR} "Keeping DBICx::TestDatabase databases: @TMPFILES\n";
    }
}

*connect = *new;

1;

__END__