2
0

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 1 year has passed since last update.

PHPUnit x Laravel よく使うスニペット まとめ

Last updated at Posted at 2022-05-20

laravel x PHPUnit で開発する際に忘れがちな処理をまとめました。

リダイレクト先で assertSee

$response = $this->post('users', [
    'name' => 'test_user',
]);

$response
    ->assertRedirect('/users')
    ->assertStatus(302);

$response->get('users')->assertSee('user一覧');
// or $this->followRedirects($response)->assertSee('user一覧');

DB定義から factory を自動生成

composer require thedoctor0/laravel-factory-generator --dev

# --recursive で directory 構成に沿って生成してくれる
php artisan generate:factory --recursive 

factory - 入れ子でまとめて生成

$this->user = User::factory(1)
    ->create()
    ->each(function ($user) {
        Post::factory(1)->create([
            'user_id' => $user->id,
        ]);
    })[0];  // collectionなので、
// Post が "user_id" を持っている場合は、 for でも行ける
$this->post = Post::factory()
    ->for(User::factory())
    ->create();

画像の保存処理

$response = $this->post('/images', [
    'name' => 'sample',
    'image' => new \Illuminate\Http\UploadedFile(
        'path_to/test.png',
        'test.png',
        null,
        null,
        true,
    )
]);

$this->assertTrue(Storage::exists('path_to/test.png'));
//  \Illuminate\Http\UploadedFile コンストラクターの定義
public function __construct(
    string $path,
    string $originalName,
    ?string $mimeType = null,
    ?int $error = null,
    bool $test = false
) { }
2
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
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?