Quantcast
Channel: Andrews' Blog
Viewing all articles
Browse latest Browse all 30

Laravel: “Allowed memory size exhausted” error during unit tests

$
0
0

I’ve been using in-memory testing for my projects based on Laravel every since I found this great  tutorial: http://net.tutsplus.com/tutorials/php/testing-like-a-boss-in-laravel-models/

It was working very well as my test cases increases, to a point when I’m starting to get this error message:

Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 16 bytes) in /Applications/AMPPS/www/project/vendor/symfony/console/Sym
fony/Component/Console/Command/Command.php on line 57

I couldn’t find the proper solution, but managed to get it working with a workaround here: http://forums.laravel.io/viewtopic.php?id=11723

We can temporarily increase the memory limit using this function:

// Temporarily increase memory limit to 256MB
ini_set('memory_limit','256M');

In my case, I needed more than 128MB of memory, so I conveniently increased it to 256MB. It depends on your usage and your hardware. Choose accordingly.

Since this is only required during my test (I follow the TDD approach, so testing comes regularly), I had added it in the TestCase class, inside method createApplication().

This is the full code in TestCase.php.

<?php

class TestCase extends Illuminate\Foundation\Testing\TestCase {

public function createApplication()
{
    // Temporarily increase memory limit to 256MB
    ini_set('memory_limit','256M');

    $unitTesting = true;
    $testEnvironment = 'testing';

    return require __DIR__.'/../../bootstrap/start.php';
}    

/**
 * Default preparation for each test
 */
public function setUp()
{
    parent::setUp();
    $this->prepareForTests();
}

/**
 * Migrates the database and set the mailer to 'pretend'.
 * This will cause the tests to run quickly.
 */
private function prepareForTests()
{
    Artisan::call('migrate');
    Mail::pretend(true);
} 

}

Viewing all articles
Browse latest Browse all 30

Trending Articles