NoTimeForCaution's avatar

Adding Factory to test POST

How can I refactor the below

$attributes = [
            'sector' => 'CARGO',
            'name' => strToUpper($this->faker->word) . ' AIRWAYS',
            'icao' => 'ABC',
            'iata' => 'AB',
];
        
$response = $this->actingAs($admin)->post('/admin/airline', $attributes)

To the following

$response = $this->actingAs($admin)->post('/admin/airline', factory(Airline::class));
0 likes
7 replies
realrandyallen's avatar
Level 44

Try:

$response = $this->actingAs($admin)->post('/admin/airline', factory(Airline::class)->raw());
Talinon's avatar

Create your factory class and then:

$response = $this->actingAs($admin)->post('/admin/airline', factory(Airline::class)->make()->toArray());
NoTimeForCaution's avatar

This actually broke the following:

$this->assertDatabaseHas('airlines', ['name' => $airline->name]);
        
$this->get($airline->path())
    ->assertStatus(200);
NoTimeForCaution's avatar

FULL TEST

public function test_an_admin_can_create_an_airline()
    {
        $admin = factory(User::class)->create();
        $admin->admin = 1;
        $admin->save();
        
        $response = $this->actingAs($admin)->post('/admin/airline', factory(Airline::class)->make()->toArray())
            ->assertStatus(200);
        
        $airline = Airline::all()->first();
        
        $this->assertDatabaseHas('airlines', ['name' => $airline->name]);
        
        $this->get($airline->path())
            ->assertStatus(200);

    }

RESPONSE:

1) Tests\Feature\AirlineTest::test_an_admin_can_create_an_airline
Expected status code 200 but received 500.
Failed asserting that false is true.
// this fails on airline->path() call
Talinon's avatar

What does the log have to say about the error? When you get a 500 status error, it means something went wrong internally, and the log file is where you can find details.

As a side note, you could consolidate your first 3 lines with:

$admin = factory(User::class)->create(['admin' => 1]);

and also, no need to fetch all your Airline models to get the first, just do Airline::first();

NoTimeForCaution's avatar

Thanks again, @talinon!

Appreciate the refactor tips and logs revealed:

testing.ERROR: Invalid argument supplied for foreach()

As I was passing string in Factory instead of array.

Please or to participate in this conversation.