arielcr's avatar

Login Test with Codeception

Hi Guys!

I'm learning Codeception using Laravel 4, and I was wondering, how do you manage to write a functional test to test a feature that requires you to be logged in order to see the page?

For example, if I test that I have to be on /posts and see "My Posts", then this would not work, because I'm not logged in, and I'll get "Log In" instead. Do I have to write the code to first test that I'm logged in for every test that requires to be logged in?

0 likes
3 replies
psmail's avatar

Yeah, I think you do. I mean ... to see a page in real life you'd need to be logged in. And functional tests aren't a world away from real life user usage.

You can separate the login part of your Codeception code out into a helper file which you can reuse. That is how JW does it so there are examples of it on this site.

austenc's avatar

I usually have a class called something like TestBase that I include with a line like this in codeception's main _bootstrap.php:

// TestBase.php is in the root tests directory
require_once('TestBase.php'); 

Then in the TestBase class, I have functions like this:

 public static function loginAsAdmin(FunctionalTester $I)
 {
  $I->amOnPage('/login');
  $I->fillField('#email', self::$admin_user);
  $I->fillField('#password', self::$admin_pass);
  $I->click('#login-btn');
  $I->see('Admin');
 }

Obviously you could go about this in a more 'functional' manner by doing something like:

Auth::loginUsingId(1);

Anyway, in your test, you can just have something like:

public function _before(FunctionalTester $I)
{
    TestBase::loginAsAdmin($I);
}

Please or to participate in this conversation.