Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 4 model unit test with Codeception - Class 'Eloquent' not found

I'm trying to use Codeception to run my Laravel 4 unit tests.

Running a test for a simple class with no dependencies works fine. But when I instantiate a model which depends on Eloquent, I get this fatal error:

PHP Fatal error: Class 'Eloquent' not found in /var/www/project/app/models/Role.php on line 4

Unit test:

<?php
use Codeception\Util\Stub;
class TestModel extends \Codeception\TestCase\Test 
{
  public function testExample()
  {
    $role = new Role;
    $role->name = 'superuser';
    $this->assertEquals('superuser', $role->name);
  }
}

Model:

<?php
class Role extends Eloquent
{
  public function users()
  {
    return $this->belongsToMany('User');
  }
}

Project structure:

I'm running vendor/bin/codecept run unit from the project root, with this file structure:

/project
  codeception.yml
  /vendor/bin/codecept
  /app
    /tests
      unit.suite.yml
      /unit
         ExampleTest.php
    /models
       Role.php
                ...etc

What am I doing wrong?

like image 445
mtmacdonald Avatar asked Oct 30 '13 09:10

mtmacdonald


1 Answers

By looking at the Codeception L4 sample app, I was able to see how to bootstrap the autoload to resolve this issue, by adding these lines to project/app/tests/_boostrap.php:

include __DIR__.'/../../vendor/autoload.php';
$app = require_once __DIR__.'/../../bootstrap/start.php';
\Codeception\Util\Autoload::registerSuffix('Page', __DIR__.DIRECTORY_SEPARATOR.'_pages');

Edit: when upgrading from Laravel 4.0 to 4.1, it is also necessary to add an extra line:

$app->boot();
like image 135
mtmacdonald Avatar answered Oct 14 '22 04:10

mtmacdonald