10
10

More than 5 years have passed since last update.

[PHP] Travis CI で mailcatcher を使ってメール送信内容をテストする

Last updated at Posted at 2014-07-20

以前 PHP から送信したメールを mailcatcher でテストする 記事を書きましたが、それを Travis CI でできるか試したらできましたので投稿します。

まずは .travis.ymlbefore_script で mailcatcher が使えるように準備します。

  1. gem コマンドで mailcatcher をインストールする
  2. PHP が mailcatcher を使うように php.ini を設定する
  3. mailcatcher を起動する
travis.yml
language: php
php:
  - 5.3
before_script:
  - gem install mailcatcher
  - phpenv config-add travis.php.ini
  - mailcatcher
script:
  - phpunit SampleTest.php

次に travis.php.inisendmail_path を下記のように設定します。記述方法については公式のドキュメントにかかれています。

travis.php.ini
sendmail_path = /usr/bin/env catchmail -f from@example.com

最後にテストコードです。mb_send_mail で送信したメールを、 mailcatcher が提供してくれる API 経由で取得して期待したものになっているか確かめます。

SampleTest.php
<?php

class SampleTest extends PHPUnit_Framework_TestCase{
  public function testMailcatcher(){
    mb_language('ja');
    mb_internal_encoding('UTF-8');
    mb_send_mail('to@example.com', 'test subject', 'test body');
    $messages = json_decode(file_get_contents('http://127.0.0.1:1080/messages'));
    $message = json_decode(file_get_contents('http://127.0.0.1:1080/messages/' . $messages[0]->id . '.json'));
    $this->assertEquals('<to@example.com>', $message->recipients[0]);
    $this->assertEquals('test subject', $message->subject);
    preg_match_all('/\n\n(.*)/', $message->source, $matches);
    $this->assertEquals('test body', mb_convert_encoding($matches[1][0], 'UTF-8', 'ISO-2022-JP'));
  }
}

動作確認できたコード一式を GitHub に置きました。
https://github.com/suzuki86/sample-of-using-mailcatcher-on-travisci

そのリポジトリに対する Travis CI でのビルドです。
https://travis-ci.org/suzuki86/sample-of-using-mailcatcher-on-travisci

10
10
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
10