Testing Laravel API, Spark with Authentication

Posted: 2018-02-04 12:51:29

Just a reminder to self, if I want to test an API I made and need to pass and api_token

<?php

namespace Tests\Feature;

use Tests\TestCase;
use Illuminate\Foundation\Testing\WithFaker;
use Illuminate\Foundation\Testing\RefreshDatabase;
use App\Quote;
use Laravel\Spark\Repositories\TokenRepository;

class QuoteControllerTest extends TestCase
{

    use RefreshDatabase;
    public function testGettingAQuoteUsingToken()
    {
        $user = factory(\App\User::class)->create();
        $team = factory(\App\Team::class)->create();
        $team->users()->attach($user->id, ['role' => "member"]);
        $quote = factory(\App\Quote::class)->create([
            'team_id' => $team->id,
            'posted_by' => $user->id
        ]);
        $token = new TokenRepository();
        $token = $token->createToken(
            $user,
            'get_quote',
            []
        )->token;
        $this->json('GET', "/api/teams/{$team->id}/quotes/random?api_token={$token}")
            ->assertStatus(200)->assertJson([
                'quote' => $quote->quote,
                'by' => $quote->by,
                'posted_by' => [
                    'email' => $user->email,
                    'name' => $user->name,
                    'avatar' => $user->photo_url
                ]
            ]);
    }

Also I made a database/factories/TeamFactory.php file:

<?php

use Faker\Generator as Faker;
use App\User;
use App\Team;

$factory->define(Team::class, function (Faker $faker) {
    return [
        "name" => $faker->word,
        "owner_id" => function() {
            return factory(User::class)->create()->id;
        }
    ];
});