Let's take a look at some helpers that Laravel provides to avoid using an assertStatus()
with the HTTP status code number and make it more readable for those who don't know those statuses by heart.
It's a personal preference. You may prefer the HTTP status code as a number, which is a standard all over the web industry, not only in Laravel, or you may choose more English human-friendly methods.
In the example below, I have taken tests from the previous lessons and changed them to use Laravel helper assertions for status names instead of HTTP status codes.
use App\Models\User;use App\Models\Product;use function Pest\Laravel\actingAs; beforeEach(function (): void { $this->user = User::factory()->create();}); test('homepage contains table product', function () { $product = Product::create([ 'name' => 'table', 'price' => 100, ]); actingAs($this->user) ->get('/products') ->assertStatus(200) ->assertOk() ->assertSee($product->name);}); test('homepage contains products in order', function () { [$product1, $product2] = Product::factory(2)->create(); actingAs($this->user) ->get('/products') ->assertStatus(200) ->assertOk() ->assertSeeInOrder([$product1->name, $product2->name]);});
See the assertOk()
vs assertStatus(200)
?
Another example is the 403 HTTP status, which means "Forbidden". For example, you have some checks in the Controller, and if a user isn't admin, they will get a forbidden page. So, in the Controller, it could simply be something like this:
use App\Models\Product;use Illuminate\View\View;use Symfony\Component\HttpFoundation\Response; class ProductController extends Controller{ // public function create(): View { abort_if(! auth()->user()->is_admin, Response::HTTP_FORBIDDEN); return view('products.create'); }}
The test with the HTTP status code would look like this:
use function Pest\Laravel\actingAs; beforeEach(function (): void { $this->user = User::factory()->create();}); // ... test('guest cannot access products page', function () { actingAs($this->user) ->get('/products/create') ->assertStatus(403);});
But, of course, we can use a Laravel helper here.
use function Pest\Laravel\actingAs; beforeEach(function (): void { $this->user = User::factory()->create();}); // ... test('guest cannot access products page', function () { actingAs($this->user) ->get('/products/create') ->assertStatus(403); ->assertForbidden(); });
There are more assertion helpers, which you can find in the Laravel documentation under the HTTP Tests page.
I would like to mention one more assertion helper, assertSuccessful()
. It is similar to assertOk()
but more flexible.
assertOk()
tests for a specific HTTP code 200assertSuccessful()
tests any HTTP status within the 200 range.It could be 200, 201, 202, etc., which basically means that no errors occurred.