Skip to content

Commit

Permalink
Test triggering an event after updating orders
Browse files Browse the repository at this point in the history
  • Loading branch information
unclexo committed Jan 11, 2023
1 parent 0c51d73 commit f684622
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 0 deletions.
17 changes: 17 additions & 0 deletions app/Http/Controllers/OrderController.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@
namespace App\Http\Controllers;

use App\Events\OrderCreatedEvent;
use App\Events\OrderUpdatedEvent;
use App\Models\Order;
use Illuminate\Validation\Rule;

class OrderController extends Controller
{
Expand All @@ -18,4 +21,18 @@ public function store()

OrderCreatedEvent::dispatch($order);
}

public function update(Order $order)
{
$attributes = \request()->validate([
'shipper_id' => ['sometimes', 'numeric'],
'name' => ['required'],
'price' => ['sometimes'],
'status' => ['sometimes', Rule::in(['pending', 'processing', 'shipped', 'cancelled', 'completed'])],
]);

$order->update($attributes);

OrderUpdatedEvent::dispatch($order);
}
}
2 changes: 2 additions & 0 deletions routes/web.php
Original file line number Diff line number Diff line change
Expand Up @@ -73,5 +73,7 @@

Route::prefix('orders')->group(function() {
Route::post('/', [OrderController::class, 'store'])->name('orders.store');

Route::patch('/{order}', [OrderController::class, 'update'])->name('orders.update');
});
});
18 changes: 18 additions & 0 deletions tests/Feature/EventTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
use App\Listeners\OrderCreationListener;
use App\Listeners\OrderDeletionListener;
use App\Listeners\OrderUpdateListener;
use App\Models\Order;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Foundation\Testing\WithFaker;
Expand Down Expand Up @@ -56,4 +57,21 @@ public function triggering_an_event_after_creating_orders()

Event::assertDispatched(OrderCreatedEvent::class);
}

/** @test */
public function triggering_an_event_after_updating_orders()
{
$this->actingAs($user = User::factory()->create());

Event::fake();

Event::assertNotDispatched(OrderUpdatedEvent::class);

$this->patch(route('orders.update', Order::factory()->create()), [
'name' => 'changed',
'status' => 'shipped',
]);

Event::assertDispatched(OrderUpdatedEvent::class);
}
}

0 comments on commit f684622

Please sign in to comment.