Hi everybody,
I'm currently working on a OpenSource Laravel API that will support the communication between personal trainers and their athletes.
For the first time, I'm trying using the Laravel GitHub action with the default configuration.
This is how the yml file look like:
name: Laravel
on:
push:
branches: [ main ]
pull_request:
branches: [ main ]
jobs:
laravel-tests:
runs-on: ubuntu-latest
steps:
- uses: shivammathur/setup-php@15c43e89cdef867065b0213be354c2841860869e
with:
php-version: '8.0'
- uses: actions/checkout@v3
- name: Copy .env
run: php -r "file_exists('.env') || copy('.env.example', '.env');"
- name: Install Dependencies
run: composer install -q --no-ansi --no-interaction --no-scripts --no-progress --prefer-dist
- name: Generate key
run: php artisan key:generate
- name: Directory Permissions
run: chmod -R 777 storage bootstrap/cache
- name: Create Database
run: |
mkdir -p database
touch database/database.sqlite
- name: Execute tests (Unit and Feature tests) via PHPUnit
env:
DB_CONNECTION: sqlite
DB_DATABASE: database/database.sqlite
run: vendor/bin/phpunit
I'll share you one of my migration, test, controller and policy:
create_category_table:
public function up()
{
Schema::create('categories', function (Blueprint $table) {
$table->id();
$table->foreignId('user_id')->constrained();
$table->string('name');
$table->string('description');
$table->timestamps();
});
}
CategoryTest:
public function test_get_category(): void
{
$user = User::factory()->create();
Sanctum::actingAs($user);
$category = Category::factory()->create(['user_id' => $user->id]);
$response = $this->get('/api/category/'.$category->id);
$response->assertStatus(200);
$response->assertJson(['status' => 'success','category' => []]);
}
CategoryController:
public function getCategory(\Illuminate\Http\Request $request): JsonResponse {
$category = Category::find($request->id);
if($category) {
if($request->user()->cannot('view', $category)) {
return response()->json(['error' => 'Unauthorized'], 401);
}
return response()->json(['status' => 'success', 'category' => $category]);
}
return response()->json(['status' => 'error', 'report' => 'Non è stata trovata nessuna categoria']);
}
CategoryPolicy:
public function view(User $user, Category $category)
{
return $user->id === $category->user_id;
}
GitHub Action:
1) Tests\Feature\CategoryTest::test_get_category
Expected response status code [200] but received 401.
Failed asserting that 200 is identical to 401.
/home/runner/work/gym-diary/gym-diary/vendor/laravel/framework/src/Illuminate/Testing/TestResponse.php:177
/home/runner/work/gym-diary/gym-diary/tests/Feature/CategoryTest.php:44
This seems to happen to every method that has a Policy.
Can anyone help me?
P.S: Of course, it works when I run the test locally
EDIT:
CategoryFactory:
public function definition()
{
return [
'name' => $this->faker->sentence(2),
'description' => $this->faker->sentence(),
'user_id' => User::factory()
];
}