Skip to content

Instantly share code, notes, and snippets.

@fideloper
Created November 11, 2013 13:55
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fideloper/7413518 to your computer and use it in GitHub Desktop.
Save fideloper/7413518 to your computer and use it in GitHub Desktop.
Example testing with in-memory SQLite database
<?php
/**
* Intention:
*
* "testing" environment has a SQLite database configured
* Run migrations against --env=testing
*
* Separate seeds run here per test method will delete the SQLite
* code tables, and re-create them with codes that fit the needs
* of the two tests here
*
* sudo apt-get update
* sudo apt-get install libsqlite3-0 php5-sqlite
*/
class CodeTest extends TestCase {
/**
* Test if you get a shipping code because there are no
* winnable codes.
*
* This happens if all codes in the past are marked as "won"
* or "deleted" where "deleted" === won and claimed
*
* This also happens when there are no codes in the past.
*
* Also implicitly tests that you cannot get a code that's
* from the future.
*/
public function testGetShippingCodeIfNoWinnableCodes()
{
$this->migrate();
$this->seed('TestUnwinnableSeeder');
$codeRepo = App::make('Namespace\Repositories\Code\CodeInterface');
// Test database should create 2 winnable codes
// and then the free shipping code
// The third code should therefore be the shipping code
$code1 = $codeRepo->nextCode(new DateTime);
$code2 = $codeRepo->nextCode(new DateTime);
$code3 = $codeRepo->nextCode(new DateTime);
$this->assertTrue($code1->code === 'ABC123');
$this->assertTrue($code2->code === 'ABC123');
$this->assertTrue($code3->code === 'ABC123');
}
/**
* Test that you win a code
*
* This happens when there is a winning code in the past
* but is not yet marked as "won" or "deleted", where
* "deleted" === won and claimed
*/
public function testGetWinningCode()
{
$this->migrate();
$this->seed('TestWinnableSeeder');
$codeRepo = App::make('Namespace\Repositories\Code\CodeInterface');
// Test database should create 2 winnable codes
// and then the free shipping code
// The third code should therefore be the shipping code
$code1 = $codeRepo->nextCode(new DateTime);
$code2 = $codeRepo->nextCode(new DateTime);
$code3 = $codeRepo->nextCode(new DateTime);
$this->assertTrue($code1->code != 'ABC123');
$this->assertTrue($code2->code != 'ABC123');
$this->assertTrue($code3->code === 'ABC123');
}
/**
* Add data tables to SQLite in-memory database
* This database only lasts per request!
*
* Anything run in tests automatically uses the
* "testing" environment
*/
protected function migrate()
{
Artisan::call('migrate');
}
}
<?php
//app/config/testing/database.php
return array(
'default' => 'sqlite',
'connections' => array(
'sqlite' => array(
'driver' => 'sqlite',
'database' => ':memory:',
'prefix' => '',
),
),
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment