Anybody knows how to avoid captcha within Unit testing (Selenium) with Yii 1.x ? I've tried to get cuurent captcha value using in my tests:
$vc_key = "Yii.CCaptchaAction." . Yii::app()->getId() . ".site.captcha";
$captchaCode = Yii::app()->session->get($vc_key);
- got empty value. Also have tried with:
$captcha=Yii::app()->getController()->createAction("captcha");
$captchaCode = $captcha->verifyCode;
And got an error: Fatal error: Call to a member function createAction() on a non-object
Got it to work with this way: 1. Add to your test config (it uses by Yii unit tests) some variable lets say, it will be "testmode":
...
'params' => array(
'testmode' => true, // to avoid captcha validation
),
...
In your model validation rules set corresponding condition. For me it is following: In rules:
array( 'verifyCode', 'captchaValid', 'allowEmpty'=>!Yii::app()->user->isGuest || !CCaptcha::checkRequirements(), 'enableClientValidation' => true, 'message'=>Yii::t('app', 'wrong code'), 'on' => array('create'), ),
Below:
public function captchaValid($field, $params) {
if(!$this->hasErrors($field))
{
if (Yii::app()->params['testmode'] == true) // here is our mark
return;
$vc_key = "Yii.CCaptchaAction." . Yii::app()->getId() . ".site.captcha";
if ( Yii::app()->session->get($vc_key) != $this->{$field} )
{
$this->addError($field, $params['message']);
}
}
}
That's all. For my case it was some additional completions, but in most of cases, approach above should work. If you will have some problems with it, let me know.