0

I am developing an app and now I need to do some testing. Everything in the app is based on authenticated user so this is the first test that I need to do. I have a google captcha in the form but I modified the .env file so that will not be required. This is my feature test.

public function test_users_can_authenticate()
{
     $user = User::factory()->create();

     $response = $this->get('/login', [
         '_token' => csrf_token(),
         'email' => $user->email,
         'password' => 'secret',
         'g-recaptcha-response' => ''
     ]);
        
     $this->assertAuthenticated();
     $response->assertRedirect(RouteServiceProvider::HOME);
}

The test is failing on this line $this->assertAuthenticated(); saying that The user is not authenticated. Failed asserting that false is true. I did not now what can I do to make it work. I tried php artisan config:clear before php artisan test, not working. I uncomment the lines in phpunit.xml

<!-- <server name="DB_CONNECTION" value="mysql"/> -->
<!-- <server name="DB_DATABASE" value=":memory:"/> -->

but still with no result. Working with Laravel 8.x. What can I do to make this work? Thanks.

3
  • I think you should use sqlite instead of mysql in your phpunit.xml: <server name="DB_CONNECTION" value="sqlite"/> Also share your routes file but i think the call should be a post and not a get Commented Mar 22, 2022 at 15:07
  • Have you stepped through the code? That said, there seems to be a lot of magic going on, starting with the User::factory(), which is as bad as a global variable. Generally, using dependency injection would be preferred, IMHO. Commented Mar 22, 2022 at 16:08
  • @rachids neither post or get is not working for the route. And with the sqlite connection from phpunit.xml it's throwing me the error could not find driver (SQL: PRAGMA foreign_keys = ON;). And the routes for the login are the ones from make:auth. Commented Mar 23, 2022 at 12:21

1 Answer 1

1

The first thing to do is for you to create a protected function in your TestCase.php like this.

protected function user()
{
    return (User::factory()->create());
}

After you do this, you can call it in the test of your application.

public function test_users_can_authenticate()
{
$this->actingAs($this->user()
->assertStatus(302);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.