![]() |
|
Snippets |
|
To use database connections defined in the databases.yml configuration file, you can use the following snippet:
// initialize database manager $databaseManager = new sfDatabaseManager(); $databaseManager->initialize();
Even though the book is quite good, the part in which unit testing is explained could use some better information. Especially the testing with a database connection (Propel in this case) needs some fixing.
Below you find an example unit test in which the database is accessed.
It tests a fictional class 'testClass' with the method 'load()'. That method accesses the database ... for which Propel needs to be running. The Symfony application that is loaded is called 'myapp';
if (!@constant('SF_APP')) { // Only load constants in not done before (group tests) define('SF_APP', 'myapp'); define('SF_ENVIRONMENT', 'dev'); define('SF_DEBUG', TRUE); } if (!@constant('SF_ROOT_DIR')) { // Only load constants in not done before (group tests) include(dirname(__FILE__).'/../bootstrap/unit.php'); } sfCore::initSimpleAutoload(array(SF_ROOT_DIR.'/lib/model' // DB model classes ,$sf_symfony_lib_dir // Symfony itself ,dirname(__FILE__).'/../../lib' // Location class to be tested ,dirname(__FILE__).'/../../apps/stageselect/lib' // Location myapp application ,SF_ROOT_DIR.'/plugins')); // Location plugins set_include_path($sf_symfony_lib_dir . '/vendor' . PATH_SEPARATOR . SF_ROOT_DIR . PATH_SEPARATOR . get_include_path()); /* * Start database connection and Symfony core */ sfCore::bootstrap($sf_symfony_lib_dir, $sf_symfony_data_dir); sfContext::getInstance(); Propel::setConfiguration(sfPropelDatabase::getConfiguration()); Propel::initialize(); /* * Test */ // Init $oTest = new lime_test(1, new lime_output_color()); // Print head $oTest->diag('testClass'); $oTest->diag('----'); // Does the method load() exist in class 'testClass' $oTest->can_ok('testClass', 'load', 'testClass has method load()');
We wanted to use a 'propel-insert-sql' in our acceptance tests suite to clear DB before every test reducing interferences. We all learned here http://www.symfony-project.com/snippets/snippet/16 how to call a Pake task from our PHP code. To get a quiet 'propel-insert-sql' task letting 'test' task be verbose and reporting test results we must add a method to the pakeTask class in pakeTask.class.php file:
public function setVerbose() { $this->verbose = false; }
and edit sfPakePropel.php file to make 'propel-insert-sql' task quiet:
function run_propel_insert_sql($task, $args) { $task->setVerbose(); _call_phing($task, 'insert-sql'); }
This way we have a lot quiter acceptance test suite and a clean DB whenever we want.