I'm setting up e2e tests using Laravel Dusk and I'm having problems trying to figure out how to test Laravel's authentication.
I am migrating a database using DatabaseMigrations
trait and populating it with 1 record ( running setUp method which mocks up a user ). I tried to login with this specific user using the loginAs()
method but it doesn't log me in.
My AuthenticationTest.php
file
use DatabaseMigrations;
public function setUp(): void
{
parent::setUp();
factory('App\User')->create();
}
public function an_authenticated_user_will_see_an_account_button()
{
$this->browse(function (Browser $browser) {
$browser
->loginAs(User::find(1))
->visit('http://recipemanager.test/recipes')
->assertSee('Account');
});
}
My dusk routes
| | GET|HEAD | _dusk/login/{userId}/{guard?} | | Laravel\Dusk\Http\Controllers\UserController@login | web |
| | GET|HEAD | _dusk/logout/{guard?} | | Laravel\Dusk\Http\Controllers\UserController@logout | web |
| | GET|HEAD | _dusk/user/{guard?} | | Laravel\Dusk\Http\Controllers\UserController@user | web |
Steps to reproduce the bug ( You need to have XAMPP ):
1. Clone the repo
2. Switch to branch account
2. Configure the .env file
to match your database
3. Make sure to configure vhosts
Apache file and etc/hosts
file so you can access recipemanager.test
as home route ( 127.0.0.1 recipemanager.test
)
4. Run php artisan dusk
Errors:
1)Tests\Browser\AuthenticationTest::an_authenticated_user_will_see_an_account_button
Did not see expected text [Account] within element [body].
Failed asserting that false is true.
I fixed the problem by visiting recipes visit('/recipes')
. The problem was in the environment file -> APP_URL was set to localhost and Dusk was trying to visit localhost:800/recipes. I checked that by asserting full URL
$this->browse(function (Browser $browser) {
$browser
->loginAs(User::find(1))
->visit('/recipes')
->assertUrlIs('http://recipemanager.test/recipes');
});
Error: Actual URL [http://localhost/recipes] does not equal expected URL [http://recipemanager.test/recipes].
.env
file
APP_URL=http://localhost
After I changed the APP_URL to http://recipemanager.test
and visit /recipes
everything is working fine!