NAME

Test::DBIC::ExpectedQueries - Test that no unexpected DBIx::Class queries are run

DESCRIPTION

Ensure that only the DBIx::Class SQL queries you expect are executed while a particular piece of code under test is run.

Avoiding the n+1 problem

When following a relation off a row object it's easy to overlook the fact that it's causing one query for each row in the resultset. This can easily be solved by prefetching those relations, but you have to know it happens first.

This module will help you with that, and to ensure you don't accidentally start running many single row queries in the future.

SYNOPSIS

Simple case

use Test::More;
use Test::DBIC::ExpectedQueries;

my $schema = ...;  # A DBIx::Class schema object

# The return value of the subref is returned
my $author_rows = expected_queries(
    # Collect stats for this schema
    $schema,
    # when running this code
    sub {
        $author_tree->create_authors_for_tabs($schema),
    },
    # and ensure these are the expected queries
    {
        # For the "tree_node" table
        tree_node => {
            update => ">= 1",  # Number of updates must be >= 1
            select => undef,   # Any number of selects are fine
        },
        # For the "author" table
        author => {
            update => 8,       # Number of updates must be exactly 8
        },
        user_session => {
            delete => "< 10",  # No more than 9 deletes allowed
        },
        # Any query on any other table will fail the test
    },
);

Flexible case

The expected queries syntax is the same as above, but using the OO interface allows you to collect stats for many separate queries.

Useful for when you care about individual return values from methods called, and when you don't know the expected number of queries until after they have been run.

use Test::More;
use Test::DBIC::ExpectedQueries;

my $queries = Test::DBIC::ExpectedQueries->new({ schema => $schema });
my $author_rows = $queries->run(
    sub { $author_tree->create_authors_for_tabs($schema) },
);

$queries->run( sub { $author_tree->check_stuff() } );

# ... test other things

my $total_author_count = @{$author_rows} + 1; # or whatever
$queries->test(
    {
        author     => {
            insert => $total_author_count,
            update => undef,
        },
        field      => { select => "<= 1" },
        tree_node  => { select => 2 },
    },
);

AUTHOR

Johan Lindstrom, <johanl [AT] cpan.org>

BUGS AND CAVEATS

BUG REPORTS

Please report any bugs or feature requests on GitHub: https://github.com/jplindstrom/p5-Test-DBIC-ExpectedQueries/issues.

KNOWN BUGS

CAVEATS

COPYRIGHT & LICENSE

Copyright 2015- Johan Lindstrom, All Rights Reserved.

This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.