afterSave() does not get called when testing?

I’m doing a simple create test. Asserting the count of records before and after saving new one. While saving the main record, I also need to add new rows to other tables, which work in relation to it. So I put the logic to save those records in afterSave() of my main ActiveRecord (named ‘List’). Here’s the code for it.



protected function afterSave()


{


	parent::afterSave();


	if ($this->isNewRecord)


	{


		$listNumber = new ListNumber;


		$listNumber->id = Helper::generateUUID();


		$listNumber->prospect_list_id = $this->id;


		$listNumber->save();


	}


}

Everything works okay when I’m manually testing this in the browser. However, doing the same thing in a unit test, new List gets saved, but new ListNumber does not. So, my guess is that afterSave() is not being called in my unit test. No idea why.

Has anyone come across this issue?

Can you post your test code? Maybe it’s just a wrong assertion that causes the test to fail.

@phtamas

Here’s the code for test.



public function testCreateList()


{


	$user = $this->getUserData();





	$this->assertEquals(2, $user->getRelated('totalLists', true)); // Check the total lists in fixture prior to creating


	


	$newList = new List;


	$newList->setAttributes(array(


		'name'=>'New List',


		'description'=>'Lorem Ipsum',


		'list_type'=>'email'


	));


	$newList->save();





	$this->assertEquals(3, $user->getRelated('totalLists', true));





	$newList = List::model()->findByPk($newList->id);


	$this->assertEquals('New List', $newList->name); 


	$this->assertEquals('email', $newList->list_type);


	$this->assertEquals($newList->id, $newList->listNumber->list_id);


}

All the assertions, except the last one, work. I also checked my test database after running this test and it shows a new entry in ‘lists’ table, but no new entry in ‘list_numbers’ table. But, when I manually create a list from the browser, the database entries for both get created.

I also have an exactly similar test written for a different model. And everything works fine in its case, because I’m not using afterSave() there. I instead put the logic for saving relational attributes inside if($model->save()) {}

So I don’t understand why this one doesn’t work.