مقاله

getJson، actingAs، assertStatus و تست flow کامل — از login تا ایجاد post با Pest و RefreshDatabase.

Feature Test در Laravel — تست HTTP، auth و JSON API

Feature Test در Laravel — تست HTTP، auth و JSON API

Unit test می‌گوید تابع درست است؛ Feature test می‌گوید «کاربر واقعاً می‌تواند post بسازد و ۲۰۱ بگیرد». برای Laravel یعنی HTTP request به kernel — routing، middleware، validation، database. این مقاله الگوی تستی است که در هر پروژه تکرار می‌کنم.

Setup

uses(RefreshDatabase::class);

beforeEach(function () {
    $this->user = User::factory()->create();
});

تست صفحه عمومی

it('shows blog index', function () {
    Post::factory()->published()->count(3)->create();
    $this->get(route('blog.index'))
        ->assertOk()
        ->assertSee('وبلاگ');
});

auth middleware

it('redirects guest from dashboard', function () {
    $this->get('/dashboard')->assertRedirect('/login');
});

it('allows authenticated user', function () {
    $this->actingAs($this->user)
        ->get('/dashboard')
        ->assertOk();
});

Breeze: احراز هویت.

POST با validation

it('stores post with valid data', function () {
    $category = Category::factory()->create();

    $this->actingAs($this->user)
        ->post('/admin/posts', [
            'title' => 'تست عنوان',
            'category_id' => $category->id,
            'content' => '<p>متن</p>',
        ])
        ->assertRedirect();

    $this->assertDatabaseHas('posts', ['title' => 'تست عنوان']);
});

it('returns 422 when title missing', function () {
    $this->actingAs($this->user)
        ->postJson('/admin/posts', [])
        ->assertUnprocessable()
        ->assertJsonValidationErrors(['title']);
});

API با Sanctum

it('returns posts via api', function () {
    Sanctum::actingAs($this->user);
    Post::factory()->published()->count(2)->create();

    $this->getJson('/api/v1/posts')
        ->assertOk()
        ->assertJsonCount(2, 'data');
});

REST API، Sanctum.

Policy

it('forbids updating others post', function () {
    $post = Post::factory()->for(User::factory())->create();
    $this->actingAs($this->user)
        ->put("/admin/posts/{$post->id}", ['title' => 'hack'])
        ->assertForbidden();
});

Policy.

نکات

  • route name نه URL hardcode
  • factory نه fixture دستی
  • هر test مستقل — RefreshDatabase
  • assertJsonStructure برای API

جمع‌بندی

Feature test = confidence deploy. مقدمه: Pest. Unit: بعدی.

CI و تست