LoginSignup
3
4

More than 5 years have passed since last update.

Laravel の結合テストで、メール送信を Mock する

Last updated at Posted at 2017-03-24

ユーザー新規登録はクリティカルなので、テストを書いておきたかった。

でも新規登録時にメールが送られて、ミドルウェアの設定をしないとそこでエラーになってしまう。
ローカル上では mailcatcher 動いているからいいけど、CI上ではそれをやりたくない。

なので Mock した。思ってたより簡単だった。

  • Laravel 5.1
tests/integratin/UserSignupTest.php
<?php

namespace Tests\Integration;

use App\Models\User;
use Tests\TestCase;

class UserSignupTest extends TestCase
{

    public function testUserSignup()
    {
        \Mail::ShouldReceive('send')
               ->once()
               ->andReturn(true);

        $this->visit('/signup')
             ->type('hoge@example.com', 'email')
             ->type('secret', 'password')
             ->press('Sign up')
             ->seePageIs('/home');

        $this->seeInDatabase('users', [
            'email' => 'hoge@example.com'
        ]);
    }
}

Mail::send() メソッドが実行されなければ、エラーが発生する。

できればメールの内容のチェックもしたい。
ShouldReceive('send')->with(...) とか使えばいいんだろうか。

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