toniperic's avatar

[Codeception] Send email when test fails

I'm using Codeception. I want to trigger tests tests via a cron job once a day at midnight (checked), and if those acceptance tests fail I'd like to be notified immediately (I guess via email).

How can I accomplish this?

0 likes
2 replies
ohffs's avatar

You could check the exit status of codeception maybe? Assuming it's well behaved and sets them properly. Something like (untested!) :

#!/bin/bash
cd /path/to/your/app
OUTPUT=`vendor/bin/codecept run 2>&1`
if [ $? ];
then
    echo "${OUTPUT}" | mailx -s 'Codeception Failed' you@somewhere.com
fi

You'll possibly need to apt-get install bsd-mailx to get the mailx command if you're on Ubuntu (or possibly 'mailutils' and it'll ask you for the smtp server etc as part of the 'Satellite server' question). Or there's possibly one of these new-fangled SaaS things your could do a curl post request to - I don't hold with such things though ;-)

toniperic's avatar
toniperic
OP
Best Answer
Level 30

Found a clear way to do it, as Codeception provides hooks.

For those wondering how I did it, continue reading.

There are Helper classes in the tests/_support/Helper directory. Since I was running acceptance tests and want to send an email if they fail, I've used the Helper\Acceptance class. It extends the Codeception\Module, which has some methods that are supposed to be used as hooks, which you can override in the Helper\Acceptance class.

So my Acceptance helper class now basically looks like this

class Acceptance extends \Codeception\Module
{

    public function _failed(TestCase $test, $fail)
    {
        // send email to myself here
    }
}

Extra Laravel-related info

If you wish to use Laravel's container to resolve something out of it, such as mailer class, you can use the Laravel5 module for Codeception, and then you can resolve the same mailer instance as you use in your Laravel app, likewise

public function _failed(TestCase $test, $fail)
{
    $mailer = $this->getApplication()->make('mailer');
    
    $mailer->send(/* whatever */);
}

This helps me in case I change from Mandrill to some other mailing service in the future.

Hope this helps someone.

Please or to participate in this conversation.