8
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Laravelではメール送信やSlack通知のテストが簡単だって知ってましたか?

Last updated at Posted at 2020-01-21

メールやSlack通知のテストしてますか?
通知のテストはし難いのですが、Laravelではモックが充実しているので簡単にテストすることができます。

参考: https://readouble.com/laravel/6.x/ja/mocking.html

環境

  • PHP v7.2
  • Laravel v6.x
  • PHPUnit v7.5

テストする方法

以下のようにpostのテストを実行する前に Mail Facade で fake を差し込むようにしておく。
postテスト実行した後に、assertSent() でMailableクラスの処理が走っているかテストできます。

use Illuminate\Support\Facades\Mail;

class IndexControllerTest extends TestCase
{
    public function testIndex()
    {
        Mail::fake();

        $this->post('/path/to/something/post', ['text' => 'ダミーテキスト'])->assertRedirect();

        // MessageCreatedクラスは、Mailableをextendsしたものです。実行されているべきMailableをフルパスで指定します。
        Mail::assertSent(MessageCreated::class);
    }
}

おまけ

notificationもテストできます。

Slack通知など。
ドキュメントの Notification Fake のところを参照してください。
「テストをかけるよ」ということを知識として知っていないとなかなかかけないのでここで紹介だけしておきます。

ハマりどころ

最初、以下のように書いて動かずにハマったので共有しておきます。

    public function testIndex()
    {

        $this->post('/path/to/something/post', ['text' => 'ダミーテキスト'])->assertRedirect();

        // postのテストが終わった後にfake差し込み
        Mail::fake();
        Mail::assertSent(MessageCreated::class);
    }

fakeを差し込むタイミングが終わった後なので意味がありません。

面倒なので毎回 fake を書きたく無い場合

setUp()のなかで処理を追加しておきましょう。
毎回クラスに書いてもいいのですが、これを差し込んだ共通親クラスを作っておくともっと楽チンです。


    protected function setUp(): void
    {
        parent::setUp();

        Mail::fake();
    }

8
3
1

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
8
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?