LoginSignup
0
0

More than 1 year has passed since last update.

laravel テストアサーション 指定Eloquentモデルが削除論理されていることを確認する

Posted at

概要

  • laravelのテストのアサーションにて指定Eloquentモデルが論理削除されたことを確認するアサーションをまとめる。

チェック方法

  • assertSoftDeletedで確認する事ができる。

  • 下記のように記載する。

    $this->assertSoftDeleted(Eloquent);
    // もしくは
    $this->assertSoftDeleted(table: テーブル名, data: ['カラム名' => ]);
    
  • 公式ドキュメントの例を借りると下記の様になる。下記の場合処理に成功していればテストが通る。

    use App\Models\User;
    
    $user = User::find(1);
    
    $user->delete();
    
    $this->assertSoftDeleted($user);
    
  • 当該のアサーションの実装箇所を見たら下記のように記載されていた。

    intractsWithDatabase.php
    /**
     * Assert the given record has been "soft deleted".
     *
     * @param  \Illuminate\Database\Eloquent\Model|string  $table
     * @param  array  $data
     * @param  string|null  $connection
     * @param  string|null  $deletedAtColumn
     * @return $this
     */
    protected function assertSoftDeleted($table, array $data = [], $connection = null, $deletedAtColumn = 'deleted_at')
    {
        if ($this->isSoftDeletableModel($table)) {
            return $this->assertSoftDeleted(
                $table->getTable(),
                array_merge($data, [$table->getKeyName() => $table->getKey()]),
                $table->getConnectionName(),
                $table->getDeletedAtColumn()
            );
        }
    
        $this->assertThat(
            $this->getTable($table), new SoftDeletedInDatabase($this->getConnection($connection, $table), $data, $deletedAtColumn)
        );
    
        return $this;
    }
    
  • そのためどうやらassertDatabaseHasと同じようにテーブル名とデータ名でレコードを特定しても論理削除チェックしてくれる。

  • 例えば「usersテーブルのidが1のレコードが論理削除されているか」の確認は下記のように記載する。

    $this->assertSoftDeleted(table: 'users', data: ['id' => 1]);
    

参考文献

0
0
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
0
0