Using Dusk with Laravel on macOS
Published February 9, 2017
Updated March 9, 2017
Laravel 5.4 has introduced some great new features, but I think one that’s really impressing a lot of people is a new package called Dusk.
Running in a virtual machine from your local (host) machine, with database migrations
If you’re using Homestead, or another virutal machine, but you launch Dusk from your host machine, you will run into problems using the database. This will seem familiar:
SQLSTATE[HY000] [2002] Connection refused (SQL: select * from information_schema.tables where table_schema = homestead and table_name = migrations)
The problem is that the migration takes place in the console, but the application takes place in the virtual machine. For example, if you’ve used the DatabaseMigrations
trait with a Dusk test.
Big shout out to one of my colleagues Stef Horner for finding this solution.
- Copy your
.env
file, and call it.env.dusk
. - Change your database name to a testing database, such as
appname_test
. - Add a new setting
HOST_DB_PORT=33060
– note the0
on the end. - Add
'host-port' => env('HOST_DB_PORT'),
toconfig/database.php
. - In your
AppServiceProvider
, add a new method (overrideDbPort
below) and add it to your boot.
In App\Providers\AppServiceProvider
:
public function boot()
{
$this->overrideDbPort();
}
/**
* Override the database port under conditions
*/
public function overrideDbPort()
{
if ($this->app->isLocal() && $this->app->runningInConsole()) {
// Override the port so you can tunnel into homestead.
if ($port = config('database.host-port')) {
config()->set('database.connections.mysql.port', $port);
}
}
}
Now, run php artisan dusk
from your host machine. It’ll run the migrations in the virtual machine, and then the application.
This has the added advantage of now all artisan
commands will run in your virtual machine from your host machine.
Still having issues? Read on.
Setting up
I had a few problems setting it up, so here’s some things to check if you’re having problems.
Make sure you’ve installed Chrome
This may sound stupid, but I don’t have Chrome installed – I tend to use Safari and Firefox. This caused a problem when running locally on my Mac, as you might imagine.
Check permissions
Dusk is installed via Composer, but it doesn’t set the binary to the correct permissions to be used by Artisan, if you’re using it locally rather than in the box you installed it from. For example, you installed it using a Vagrant box (like Homestead), but you’re running your tests locally on your computer.
This will fix that problem:
chmod -R 0755 vendor/laravel/dusk/bin
Check your .env
file has the correct APP_URL
You often forget to do this at the start of your project, but check your .env
file for APP_URL
. It has to be correct for Dusk to be able to load the page.