Testing with Laravel Sail and Cypress

posted by 3 years ago and updated 3 years ago

Testing is always an important element to pushing code that works. Or that code that if it breaks we can easily fix.

Setting things up for testing can always be a pain.

For this guide we will be using a package laracasts/cypress

Follow the Installation and Environment Handling sections in Readme.md and then proceed with the following amendments.

Edit: cypress/support/index.js to stop the swapping of the .env files

before(() => {
    // cy.task('activateCypressEnvFile', {}, { log: false });
    // cy.artisan('config:clear', {}, { log: false });

    cy.refreshRoutes();
});

after(() => {
    // cy.task('activateLocalEnvFile', {}, { log: false });
    // cy.artisan('config:clear', {}, { log: false });
});

Run sail using .env.cypress

sail --env-file .env.cypress up

Create a separate database

Yes it is possible to run tests on a separate database, you just have to create it.

Sail does not provide sqlite, there might be a way to install it and configure it but I didn't find anything.

Credit for this goes to: https://michaelheap.com/laravel-sail-test-database/

Edit .env.cypress

DB_CONNECTION=mysql
DB_HOST=mysql_test
DB_DATABASE=
DB_USERNAME=root

Edit docker-compose.yml to create a new database

services:
   mysql_test:
        image: "mysql:8.0"
        environment:
            MYSQL_ROOT_PASSWORD: "${DB_PASSWORD}"
            MYSQL_DATABASE: "${DB_DATABASE}"
            MYSQL_USER: "${DB_USERNAME}"
            MYSQL_PASSWORD: "${DB_PASSWORD}"
            MYSQL_ALLOW_EMPTY_PASSWORD: "yes"
        networks:
            - sail

Photo by Tim Borodin on Unsplash

Do you need help? Sometimes it is just easier to ask

In case you need that little extra push with your project. We are always happy to collaborate with new people in the industry.

Contact us for help