テスト用シーディングができない - d-sazanami/laravel-jissenkaihatsu-v1 GitHub Wiki

現象

# php artisan db:seed --database=testing --class=PersonSeeder

   Illuminate\Database\QueryException 

  SQLSTATE[HY000] [2002] Connection refused (SQL: insert into `people` (`name`, `mail`, `age`) values (博麗霊夢, [email protected], 16))

  at vendor/laravel/framework/src/Illuminate/Database/Connection.php:712   
    708▕         // If an exception occurs when attempting to run a query, 
we'll format the error
    709▕         // message to include the bindings with SQL, which will make this exception a
    710▕         // lot more helpful to the developer instead of just the database's errors.
    711▕         catch (Exception $e) {
  ➜ 712▕             throw new QueryException(
    713▕                 $query, $this->prepareBindings($bindings), $e
    714▕             );
    715▕         }
    716▕     }

      +16 vendor frames
  17  database/seeders/PersonSeeder.php:18
      Illuminate\Database\Query\Builder::insert()

      +22 vendor frames
  40  artisan:37
      Illuminate\Foundation\Console\Kernel::handle()

対応

MYSQLの設定見直し

権限設定をしたときにし忘れたので実行してみる

FLUSH PRIVILEGES;

特に変わらず

コマンドが間違っていた

testing環境のデータベースへアクセスするには、 --database パラメータではなく、 --env パラメータを使うのが正しかった。--env パラメータに testing を指定することで、マイグレーションの確認も、seederも適応できた。

# php artisan migrate:status --env=testing
+------+------------------------------------------------+-------+
| Ran? | Migration                                      | Batch |
+------+------------------------------------------------+-------+
| Yes  | 2014_10_12_000000_create_users_table           | 1     |
| Yes  | 2014_10_12_100000_create_password_resets_table | 1     |
| Yes  | 2019_08_19_000000_create_failed_jobs_table     | 1     |
| Yes  | 2022_03_05_010816_create_people_table          | 1     |
| Yes  | 2022_03_05_034018_add_age_to_people            | 1     |
| Yes  | 2022_03_09_025533_create_jobs_table            | 1     |
+------+------------------------------------------------+-------+
# php artisan db:seed --env=testing --class=PersonSeeder
Database seeding completed successfully.

MySQLへCLIで接続したら、データもちゃんと入っていた

ref

https://qiita.com/sola-msr/items/a09b857c5e7f7c88d01d