Developers

Testing an Email Series Without Sending an Email

Published

A five-step series that waits days between steps is awkward to test. You can’t wait five days, you can’t email real customers, and a test that fakes the data tells you about the fake, not your site.

This is how Follow-up Emails, a premium add-on for Super Speedy Emails, is tested: real WooCommerce orders, Super Speedy Emails’ real daily run, log-only mode so nothing leaves the site, and time moved by rewriting timestamps rather than waiting. Then each test is made to fail on purpose, once, to prove it tests what it says.

Available since Super Speedy Emails 1.38.0. Follow-up Emails needs Super Speedy Emails 1.38.1 or later.

Log-only mode, and why a rehearsal must not count

Super Speedy Emails has a log-only test mode. A run goes through every step (the audience, the suppression gate, the type’s callbacks, rendering, queueing) and writes each email to the log with no email sent. See Test Modes (Safe Sending).

For a staged series there’s a catch. If the engine picked each person’s next step by counting all of their log rows, a rehearsal’s rows would count too: two log-only runs of a three-step sequence, then live, and the first live email would be step 3. Super Speedy Emails counts steps separately for each send mode, so a log-only rehearsal has its own track, and the first live email is step 1.

Drive the real system, not a copy of it

The add-on’s tests run on a dedicated test site, never the main development site, and they use the real thing at every point:

  • Real purchases. Each buyer is a real WooCommerce guest order moved through pending, processing and completed, so Super Speedy Emails’ own order handler creates the subscriber and the ownership row.
  • Real records, created through Super Speedy Emails’ own record API (SSE_Support_Rules::create()), with each step’s delay stored in its settings.
  • The real daily run. Each simulated day calls the engine’s daily_check() and drains the queue, in a fresh PHP process, the way the hourly cron runs it.
  • Real assertions. The tests read the email log: the subject with its placeholders filled, the step number the engine logged, and the send mode.

A small must-use plugin keeps the site safe: it pins log-only mode, captures anything that reaches wp_mail to a file, blocks outgoing HTTP and turns off WP-Cron, so nothing runs behind the tests.

The harness, piece by piece

The safety must-use plugin

Log-only mode stops Super Speedy Emails sending, but it is not the only thing on a WooCommerce site that sends email. WooCommerce’s own order emails (new order, processing, completed) go through the real wp_mail() on every status change your fixtures make. On a test machine with no mail server they fail noisily; on one with a mail server they reach whatever address the fixture used. Capture them:

<?php
/**
 * Plugin Name: Test site safety
 * Description: Nothing leaves this machine. Test sites only.
 */
if ( ! defined( 'DISABLE_WP_CRON' ) ) {
    define( 'DISABLE_WP_CRON', true );            // the tests run the daily check themselves
}

// Pin Super Speedy Emails to log-only, whatever the settings screen says.
add_filter( 'pre_option_sse_test_mode', function () {
    return 'log_only';
} );

// Every wp_mail() call (WooCommerce's order emails included) goes to a file instead.
add_filter( 'pre_wp_mail', function ( $null, $atts ) {
    $to = is_array( $atts['to'] ) ? implode( ',', $atts['to'] ) : $atts['to'];
    file_put_contents( WP_CONTENT_DIR . '/captured-mail.log', gmdate( 'c' ) . " {$to} | {$atts['subject']}\n", FILE_APPEND );
    return true;                                  // reported as sent; nothing reached a mail server
}, 10, 2 );

// No outgoing HTTP: provider APIs, licence checks, update checks.
add_filter( 'pre_http_request', function () {
    return new WP_Error( 'blocked', 'Outgoing HTTP is blocked on this test site.' );
}, 10, 3 );

Save it as wp-content/mu-plugins/zz-test-safety.php on the test site only. Every email Super Speedy Emails would have sent is in its own log with test mode log_only; everything else is in captured-mail.log.

The switches a scheduled run needs

SSE_Support_Emails::daily_check() is the scheduled entry point (the hourly sse_support_email_check cron event calls it). It sends nothing on a fresh install until these hold:

PreconditionDefaultFor the tests
Scheduled sending unpausedPaused (sse_support_emails_paused is 1 until resumed)SSE_Support_Emails::set_paused( false );
The schedule’s day and hourEvery day, at the site-local hour of the next scheduled sse_support_email_check event, else 14:00SSE_Support_Emails::set_schedule( array( 'days' => array( 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday' ), 'hour' => 0 ) ); so any time of day is “after the send hour”
The record is activeRecords start as draftsCreate it with 'status' => 'active'
The record has not run todayOne run per record per site-local day, from its last_run_atMove last_run_at back with the other timestamps (below)

daily_check() queues; it does not send. Call SSE_Email_Queue::drain() after it, as the every-minute sse_drain_email_queue event would, so each log row reaches its final status. In log-only mode draining sends nothing and marks the row sent. The engine’s own stage history (sent_stages()) counts a row from the moment it is queued, so a type’s gate sees it either way, but assert on drained rows: that is what a real day ends with.

One simulated day, run with wp eval-file day.php in a fresh process each time (your add-on registers its type on load, as in production):

<?php
// day.php
SSE_Support_Emails::set_paused( false );
SSE_Support_Emails::set_schedule( array(
    'days' => array( 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday' ),
    'hour' => 0,
) );
$summary = SSE_Support_Emails::daily_check();   // plans and queues every due record
$drained = SSE_Email_Queue::drain();            // log-only: rows marked sent, no email
printf( "mode=%s checked=%d due=%d queued=%d drained=%d\n",
    $summary['mode'], $summary['checked'], $summary['due'], $summary['queued'], $drained );

mode in the summary is the send mode the run used. Make the harness stop if it is anything but log_only.

Moving a day, in code

<?php
// shift.php: move one fixture buyer, and everything written about them, back 24 hours.
global $wpdb;
$email     = 'buyer-01@example.test';
$record_id = 12;

foreach ( wc_get_orders( array( 'billing_email' => $email, 'limit' => -1 ) ) as $order ) {
    $order->set_date_created( $order->get_date_created()->getTimestamp() - DAY_IN_SECONDS );
    if ( $order->get_date_completed() ) {
        $order->set_date_completed( $order->get_date_completed()->getTimestamp() - DAY_IN_SECONDS );
    }
    $order->save();
}
// Wipe and re-derive this buyer's ownership rows from the moved orders.
SSE_Product_Owners::recompute_for_subscriber( SSE_Subscribers::get_by_email( $email ) );

$wpdb->query( $wpdb->prepare( "UPDATE {$wpdb->prefix}sse_email_log   SET created_at = created_at - INTERVAL 1 DAY WHERE email = %s", $email ) );
$wpdb->query( $wpdb->prepare( "UPDATE {$wpdb->prefix}sse_email_queue SET created_at = created_at - INTERVAL 1 DAY, next_attempt_at = next_attempt_at - INTERVAL 1 DAY WHERE email_log_id IN ( SELECT id FROM {$wpdb->prefix}sse_email_log WHERE email = %s )", $email ) );
$wpdb->query( $wpdb->prepare( "UPDATE {$wpdb->prefix}sse_support_rules SET last_run_at = last_run_at - INTERVAL 1 DAY WHERE id = %d", $record_id ) );

Use recompute_for_subscriber(), not SSE_Product_Owners::rebuild_for_order(). rebuild_for_order() only adds: it keeps the later of the stored and the new last_purchased_at, so after you move an order back it leaves the ownership date where it was, and the buyer never gets any older. recompute_for_subscriber() deletes the buyer’s ownership rows (and their owner meta) and re-derives them from their paid orders, which is what moving time needs.

The suite this article describes goes one step further and reads the date columns from information_schema, so a table that gains a date column is shifted too; the version above lists them by hand to show what moves.

Moving time without waiting for it

To make a day pass, the tests move every timestamp the system wrote for the test’s fixtures back 24 hours: the order dates (through WooCommerce’s own CRUD, then the ownership rows are re-derived with recompute_for_subscriber()), the fixture’s email log and queue rows, and each record’s last-run time. The date columns are read from information_schema rather than listed by hand, so a new column can’t be missed. Nothing is inserted that the system didn’t write itself.

The opposite approach, inserting rows that say “this was sent yesterday”, tests whatever your insert looks like. The real system might never write that row.

Two more rules:

  • Don’t run across midnight. The suite refuses to start within 15 minutes of UTC midnight, because a case straddling the real date change would see two days in one.
  • Don’t tidy the machine’s quirks away. The test site’s database clock runs at UTC+2, and the suite leaves it like that. Case 11 checks that a step sent at 23:00 UTC yesterday, which that clock stores as 01:00 today, doesn’t count as today’s send. Forcing the database to UTC would make the case pass whatever the code does.

What the cases cover

CaseProves
01 BackfillA 200-day-old owner gets step 1 only, then one a day; a second same-day run sends nothing
02 Strict orderStep 2 with a 1-day delay never goes before step 1 with a 5-day delay
03 New buyerNothing on the purchase day; each step waits its delay
04 Missed daysFour days without a run, then step 1 only, then one a day
05 One per dayOne follow-up a day across two records and across two products
06 Series completeNothing after the last step, even after a repeat purchase
07 Bundle ownerLeft out by default, included once “Also email people who bought this product as part of a bundle” is ticked
08 PreviewPreview, content preview and describe-series write nothing
09 Describe seriesThe ability’s answers, including that “due now” matches the next run
10 Site timezoneOn Pacific/Auckland, step 1 still goes at day 1
11 DB clock day boundaryA step sent at 23:00 UTC yesterday doesn’t count as today’s
12 Exact dayAn “exactly on day 2” step goes on day 2 and not day 1, despite a 5-day minimum gap
13 Exact day missedAn exact step whose day had no run is never sent, the next step still goes, and describe-series reports exact_day_missed with the date it was due
14 Exact backfillA 200-day buyer gets every not-sooner-than step one a day, skips the exact steps whose days have passed, and gets a later exact step on its day
15 Exact last missedA series whose last step is a missed exact step is complete and never sends again
16 Exact wins its dayAn exact step due today goes ahead of a waiting catch-up step, which follows the next day
17 Exact and one per dayExact steps ignore one-per-day, and an exact send counts as that day’s follow-up for another record’s not-sooner-than step
18 Many stepsA 25-step record keeps all 25, and a 200-day buyer gets steps 1 to 25, one a day, then nothing

Against Super Speedy Emails 1.38.1, all 18 cases pass, 284 assertions. Case 11 tests Super Speedy Emails rather than the add-on: it fails on any core whose per-day guard compares the database clock’s timestamps with a UTC string, and the add-on doesn’t work around that.

Case 08 is worth a note. A preview must be side-effect-free, and the test fingerprints the Super Speedy Emails tables (log, queue, owners, records, subscribers) and the options table before and after. The one write it allows is the content preview minting a missing unsubscribe token, so the rendered unsubscribe link is real, and the test asserts that this is the only change.

Negative controls: make each test fail for its reason

A green test is a claim. Until you’ve seen it go red for the reason it names, you don’t know whether it tests that reason or nothing at all.

The add-on has a script for this. For each case it breaks the one check that case claims to guard, runs the case and requires a failure, restores the code and requires a pass. It copies the source first and restores it on every exit path, and if the text it means to change isn’t found it reports CONTROL BROKEN rather than quietly testing unchanged code.

CaseCheck brokenRed because
01 BackfillDelay as “exactly N days”Backfilled owner got nothing on day 1
02 Strict orderDelay read from the wrong stepStep 1 went at age 3
03 New buyerNo delay checkStep 1 on the purchase day
04 Missed daysDelay as “exactly N days”Nothing after downtime
05 One per dayOne-a-day check offTwo emails on day 1
06 CompleteComplete series still dueLast step re-sent on days 3 to 5
07 BundleBundle row counted as directBundle owner got step 1 on day 1
08 PreviewAn option written in the gateOption snapshot changed during preview
09 Describe“Due now” always trueOld owner reported due on the day step 1 went
10 TimezonePurchase date read as UTCPurchase moment and due time 13 hours late
12 Exact dayExact step obeys the minimum gapNothing sent on day 2
13, 14, 15 Missed exact stepsMissed exact steps treated as never missedThe missed step sent late, or the series not complete
16 Wins its dayExact step doesn’t win its dayThe catch-up step went instead
17 One per dayExact step obeys one-per-dayOnly one of the two follow-ups on day 1
18 Many stepsA 10-step limitThe 25-step record refused (sse_stage_count) and nothing sent

Every control turns its case red, then green again. Case 11 has no control, because the check it guards is in Super Speedy Emails. One honest gap: case 01’s “a second run the same day sends nothing” is guarded twice, by the engine’s per-day guard and by the add-on, so no single change to the add-on can turn it red. Its control breaks the delay rule instead, and the test notes say so.

Leave the evidence

Each case clears the previous run’s fixtures on the way in, and nothing is torn down at the end. After a run you can log in to the test site and see exactly what the last case left: the orders, the records, the log rows. A suite that tidies up after itself destroys the one thing you’d want to look at when it fails.

Prompt to give your AI

Write end-to-end tests for my Super Speedy Emails series on a dedicated test site
in log-only mode. Create buyers with real WooCommerce orders taken through to
completed. Add a must-use plugin that pins sse_test_mode to log_only, captures
wp_mail through pre_wp_mail and blocks outgoing HTTP. For each simulated day, in a
fresh process, unpause scheduled sending, set the schedule hour to 0, run
SSE_Support_Emails::daily_check() and then SSE_Email_Queue::drain(). Move time by
shifting the timestamps the system wrote back 24 hours (orders through WooCommerce
CRUD followed by SSE_Product_Owners::recompute_for_subscriber(), log and queue rows,
the record's last_run_at), never by inserting rows yourself. Assert on the email log. Then write a negative
control for each test that breaks the one check it guards and requires a failure.
Clear fixtures at the start of each test and never tear the site down.

Further reading

Written for Super Speedy Emails 1.38.2.

Comments