DEV Community

DragosTrif
DragosTrif

Posted on

Generate Fixtures for Rose::DB ORM

A while a go I released on Metacpan DBD::Mock::Session::GenerateFixtures. So lets how can we mock data for Mysql/Maria db via Rose::Ddb ORM.

So lets install this:

sudo apt-get install -y mysql-server mysql-client libmysqlclient-dev
cpanm DBD::Mock::Session::GenerateFixtures
Enter fullscreen mode Exit fullscreen mode

At this point we can work on our unit test:

use Test2::V0;

use lib        qw(lib);

use DBI;
use Data::Dumper;
use DBD::Mock::Session::GenerateFixtures;
use Rose::DB::Object::Loader;
use Sub::Override;
use File::Path qw(rmtree);

# first connect to your db
my $db = DB->new(
    domain => 'mysql',
    type   => 'mysql'
);

# pass the real dbh to DBD::Mock::Session::GenerateFixtures
my $mock_dumper = DBD::Mock::Session::GenerateFixtures->new({dbh => $db->dbh()});

my $num_rows_updated = DB::Media::Manager->update_media(
        set => {
            location => '/data/music/claire_de_lune.ogg',
        },
        where => [
            id => 2,
        ],
    );

is($num_rows_updated, 1, 'update media table is ok');
Enter fullscreen mode Exit fullscreen mode

After the data is collected an JSON file it can be accessed by our test in the next run. Some extra lined need to be added for insert, update and delete to work as expected.


my $mock_dumper = DBD::Mock::Session::GenerateFixtures->new();
# get the mocked dbh
my $dbh         = $mock_dumper->get_dbh();

my $override = Sub::Override->new();
my $last_insert_id    = 4;
my $update_or_deleted = 1;
# override the dbh
$override->replace('Rose::DB::dbh' => sub {return $dbh});
# override last inserted id
$override->replace('Rose::DB::MySQL::last_insertid_from_sth' => sub {$last_insert_id++; return $last_insert_id});
# override rows 
$override->replace('DBD::Mock::st::rows' => sub {return 1});
Enter fullscreen mode Exit fullscreen mode

A full unit test example can be seen here:
test_rose_db_with_mysql
Bibliography
Rose::DB ORM
Generate Fixtures for DBD::Mock::Session
Testing with a real database

Top comments (1)

Collapse
 
henq profile image
henq

Good to see Rose::DB is still worked with ! I always liked it very much , concise but enough features to support full applications. DBIx::Class maybe may have a much wider support, but Rose is my favourite!