rudexpunx's avatar

Dusk test: Browser apparently works with different DB

My test

<?php

namespace Tests\Browser;

use App\Models\User;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Support\Facades\Hash;
use Laravel\Dusk\Browser;
use Tests\DuskTestCase;

class LoginTest extends DuskTestCase
{
    use DatabaseMigrations;

    /** @test */
    public function testLogin()
    {
        $user = factory(User::class)->create([
            'email' => '[email protected]',
            'password' => Hash::make('password'),
        ]);

        $this->browse(function ($browser) use ($user) {
            $browser->visit('/login')
                    ->type('input[name=email]', $user->email)
                    ->type('input[name=password]', 'password')
                    ->press('Login')
                    ->screenshot('login-page')
                    ->assertPathIs('/');
        });
    }
}

Generated screenshot says, there is no such table users, but if I dump Users::all() within the test code, it shows user correctly, using correct DB connection. I am wondering, how to set up the database for the browser, so I test against the same data I work with in my test?

Thanks in advance.

0 likes
3 replies
bearcodi's avatar

Hi @rudexpunx

I've had a similar issue when starting using Laravel Dusk.

If your unit/feature tests are using a sqlite and the :memory: database shortcut, your dusk tests won't work as dusk is simulating actually running the test through the browser.

You need to setup a .env.dusk.{environment} file and run your migrations/seeds on a sqlite and then local database file, ie databases\testing.sqlite in order for your dusk tests to work.

See Dusk environment handling for more info.

Hope this helps

Cheers

rudexpunx's avatar

Thanks a lot @bearcodi

The :memory: was the catch... File based SQLite DB works fine, but it takes time. Single stupid simple test runs like 3-4 seconds. I can run 100 backend test in such time.

Any hints for speeding up Dusk tests?

bearcodi's avatar

Dusk tests will tend to run slower that your feature/unit tests as a headless chrome instance is booted per test.

You could try using brianium/paratest this package will run your tests in parallel, depending on how many CPUs you have this could speed up your dusk tests.

Another option is to turn on PHPUnit's caching in your phpunit.xml, this will only remember the tests that have failed:

<?xml version="1.0" encoding="UTF-8"?>
<phpunit cacheResult="true"
         ...>

Then you run ./vendor/bin/phpunit --order-by=defects --stop-on-defect to only run the failed tests.

When the failed tests pass it will continue all the tests, so in case anything fails as a result of your fix your still covered.

Check this article out for expanded tips https://laravel-news.com/tips-to-speed-up-phpunit-tests

Cheers

Please or to participate in this conversation.