Search code examples
laravelunit-testinglaravel-9

Laravel Tests assertEquals says Target class [request] does not exist


I am writing a test in Laravel like this (only the relevant part):

namespace Tests\Feature\Response;

use App\Models\Customer;
use Tests\TestCase;

class ResponseTest extends TestCase
{
    protected $customer;

    public function setUp(): void
    {
        parent::setUp();

        $this->customer = Customer::factory()->enabled()->create();
    }

    public function testJson(): void
    {
        $responseData = (object) ['code' => 'NOT OK'];

        // Test its response
        $this->assertEquals('OK', $responseData->code, 'response data did not respond OK');
    }
}

But instead of giving me the message "response data did not respond OK" it responds with "Target class [request] does not exist".

The relevant part of the factory look like this:

public function enabled()
{
    return $this->state(function (array $attributes) {
        return [
            'enabled' => 1
        ];
    });
}

The relevant part of the Customer Model:

public static function boot()
{
    parent::boot();

    $request = request();
}

Oddly enough: when I don't use the state "enabled()" the problem does not occure. What am I doing wrong.


Solution

  • Well, your issue is fairly obvious, you have request inside the boot function, when a request is not always available.

    As another user stated, NEVER involve contexts that are specific, into broad systems, like a model. You can definitely use a model in a CLI or Job/Listener context, so you do not or could not have a request available...

    And you are also just doing $request = request();, that does absolutely nothing. Delete the whole boot function, you do not need it at all (at least in the context/code you shared)