I’m using SQL Server instead of MySQL and when I try to pass the unit test in ProjectTest.php the test fails in testIsInRole()…
public function testIsInRole()
{
$row1 = $this->projUserRole['row1'];
Yii::app()->user->setId($row1['user_id']);
$project=Project::model()->findByPk($row1['project_id']);
$this->assertTrue($project->isUserInRole('member'));
}
When I run the test I get the following…
% phpunit unit/ProjectTest.php
...
Time: 1 second, Memory: 10.00Mb
There was 1 failure:
1) ProjectTest::testIsInRole
Failed asserting that false is true.
...
FAILURES!
Tests: 7, Assertions: 16, Failures: 1.
I solved the failure but I’m newbie on Yii and I want to know if the solution is right.
[SOLUTION]
The fails occurs on Project::isUserInRole() method, exactly in the return, when calls the execution of the query:
public function isUserInRole($role)
{
$sql = "SELECT role FROM tbl_project_user_role WHERE project_id=:projectId AND user_id=:userId AND role=:role";
$command = Yii::app()->db->createCommand($sql);
$command->bindValue(":projectId", $this->id, PDO::PARAM_INT);
$command->bindValue(":userId", Yii::app()->user->getId(), PDO::PARAM_INT);
$command->bindValue(":role", $role, PDO::PARAM_STR);
return $command->execute()==1 ? true : false;
}
The problem is that sql statement is a non-query. In the CDbCommand documentation says:
CDbCommand::execute() returns the number of rows affected by the DELETE, INSERT, or UPDATE statement executed by the corresponding statement object. If the SQL statement executed was a SELECT, some databases may return the number of rows returned by that statement. However, this behaviour is not guaranteed for all databases. SQL Server does not return the number of rows affected by a SELECT statement.
Instead, I used CDbCommand::queryScalar() with a SELECT COUNT(*) statement to retrieve the number of rows that will be returned.
My final Project::isUserInRole() method is as follows:
public function isUserInRole($role)
{
$sql = "SELECT COUNT(role) AS num_rows FROM project_user_role WHERE project_id=:projectId AND user_id=:userId AND role=:role";
$command = Yii::app()->db->createCommand($sql);
$command->bindValue(":projectId", $this->id, PDO::PARAM_INT);
$command->bindValue(":userId", Yii::app()->user->getId(), PDO::PARAM_INT);
$command->bindValue(":role", $role, PDO::PARAM_STR);
return $command->queryScalar() == 1 ? true : false;
}
Note that I added the COUNT statement to the query and I replaced $command->excecute() by $command->queryScalar() and now when I run phpunit the test pass OK.
% phpunit unit/ProjectTest.php
PHPUnit 3.6.11 by Sebastian Bergmann.
...
Time: 1 second, Memory: 10.00Mb
OK (7 tests, 16 assertions)
What do you think about this solution? Is there another way to solve this?