What is best solution for truncate database on each test start? I'm have InnoDB engine with foreigh keys, yii can't truncate table.
If you extend CDbTestCase
and use the built in public $fixtures
property to specify your fixture files, it will handle this automatically.
However, if you built your own fixture generating system, or otherwise want to truncate a table, you can use the following.
$this->getFixtureManager()->checkIntegrity(false);
$this->getFixtureManager()->truncateTable('table_name');
$this->getFixtureManager()->checkIntegrity(false);
This again assumes you are extends CDbTestCase
for your unit test files. If you are not, then you can directly remove the integrity checks like so:
Yii::app()->db->createCommand('set foreign_key_checks=0')->execute();
//do whatever, including truncating
Yii::app()->db->createCommand('set foreign_key_checks=1')->execute();
That will also temporarily disable the foreign key checks.
Just to add a reference for Yii2 (as there are no easy to find examples):
$this->db->createCommand()->checkIntegrity(false)->execute();
$this->truncateTable('table_name');
$this->db->createCommand()->checkIntegrity(true)->execute();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With