Solucionando el error “Connection refused” al ejecutar tests de PHPUnit en GitHub Actions

Hace poco me encontré con un error bastante común (pero frustrante) al ejecutar tests de PHPUnit en GitHub Actions usando Laravel. Localmente todo funcionaba perfecto, pero en CI los tests fallaban inmediatamente con un error de conexión a la base de datos.

El problema

Al ejecutar los tests en GitHub Actions, aparecía el siguiente error:

Illuminate\Database\QueryException: SQLSTATE[08006] [7] connection to server at "127.0.0.1", port 5432 failed: Connection refused
Is the server running on that host and accepting TCP/IP connections?

Esto ocurría al intentar correr un test básico:

Tests\Feature\Auth\AuthenticationTest::test_login_screen_can_be_rendered

¿Qué significa este error?

Laravel intenta conectarse a PostgreSQL
Pero en GitHub Actions no hay ningún servidor de PostgreSQL corriendo

La solución: configurar PostgreSQL como servicio

La solución es bastante sencilla: debemos declarar PostgreSQL como un servicio dentro de nuestro workflow de GitHub Actions. Así, GitHub levantará automáticamente un contenedor con PostgreSQL antes de ejecutar los tests.

Edita el archivo .github/workflows/tests.yml

name: tests

on:
  push:
    branches:
      - develop
      - main
      - master
      - workos
  pull_request:
    branches:
      - develop
      - main
      - master
      - workos

jobs:
  ci:
    runs-on: ubuntu-latest
    environment: Testing
    strategy:
      matrix:
        php-version: ['8.4']

    services:
      postgres:
        image: pgvector/pgvector:pg16
        env:
          POSTGRES_USER: laravel
          POSTGRES_PASSWORD: secret
          POSTGRES_DB: laravel_db_test
        options: >-
          --health-cmd pg_isready
          --health-interval 10s
          --health-timeout 5s
          --health-retries 5
        ports:
          - 5432:5432

    steps:
      - name: Checkout code
        uses: actions/checkout@v6

      - name: Setup PHP
        uses: shivammathur/setup-php@v2
        with:
          php-version: ${{ matrix.php-version }}
          tools: composer:v2
          coverage: xdebug

      - name: Setup Node
        uses: actions/setup-node@v4
        with:
          node-version: '22'

      - name: Install Node Dependencies
        run: npm i

      - name: Add Flux Credentials Loaded From ENV
        run: composer config http-basic.composer.fluxui.dev "${{ secrets.FLUX_USERNAME }}" "${{ secrets.FLUX_LICENSE_KEY }}"

      - name: Install Dependencies
        run: composer install --no-interaction --prefer-dist --optimize-autoloader

      - name: Copy Environment File
        run: cp .env.example .env

      - name: Generate Application Key
        run: php artisan key:generate

      - name: Build Assets
        run: npm run build

      - name: Run Tests
        run: ./vendor/bin/phpunit

Ajustes adicionales necesarios

No olvides actualizar tu archivo phpunit.xml, debe tener

<env name="DB_CONNECTION" value="pgsql"/>
<env name="DB_DATABASE" value="laravel_ia_test"/>
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments