A simple trick to auto-retry pesky Dusk tests

If you have a Dusk test suite of reasonable size, I guarantee you there are a few pesky tests that fail intermittently and unpredictably. If you’ve ever tried to manipulate a DatePicker or a Select2 dropdown from Dusk, you know exactly what I’m talking about.

Let me show you a little trick I use (2 lines of code) that will automatically run your test again if it fails. This can save you from loads of false-negatives.

Drumroll, please…
Introducing…

Laravel’s retry() helper function!

It’s a little helper function that catches exceptions and re-runs the provided code however many times you specify. Check it out:

Before:

class IsAcceptanceTestingEvenWorthIt extends TestCase  
{
    /** @test */
    public function select_something_from_a_freaking_dropdown()
    {
        $this->browse(function ($browser) {
            $browser->visit('/some-page')
                    ->click('div > .select2 > .select2sucksatnamingclasses')
                    ->waitFor('.select2 > .select2options > .ifihadanickleforeverytimeipunchedawalldealingwiththesekindsoftests')
                    ->click('.select2 > .select2options > .ifihadanickleforeverytimeipunchedawalldealingwiththesekindsoftests');
        });
    }
}

After:

class IsAcceptanceTestingEvenWorthIt extends TestCase  
{
    /** @test */
    public function select_something_from_a_freaking_dropdown()
    {
        retry($times = 2, function () {
            $this->browse(function ($browser) {
                $browser->visit('/some-page')
                        ->click('div > .select2 > .select2sucksatnamingclasses')
                        ->waitFor($selector = '.select2 > .select2options > .ifihadanickleforeverytimeipunchedawalldealingwiththesekindsoftests')
                        ->click($selector);
            });
        });
    }
}

That’s it! Not the most beauteous bit of code I’ve ever written, but it does the job.

Fair warning: this is most definitely a band-aid. If you find yourself relying on this often, you probably need to re-evaluate your testing strategy. Treat this more like a last-resort kind of thing.

Hope you found something useful here!

TTFN,
- Caleb