I'm trying to simulate what Ardent
package is doing. Which is validating a model right before saving.
I've created this BaseModel
(According to Laravel Testing decoded
book). And added this code :
class BaseModel extends Eloquent {
protected static $rules = [];
public $errors = [];
public function validate(){
$v = Validator::make($this->attributes, static::$rules);
if($v->passes()) {
return true;
}
$this->errors = $v->messages();
return false;
}
public static function boot(){
parent::boot();
static::saving(function($model){
if($model->validate() === true){
foreach ($model->attributes as $key => $value) {
if(preg_match("/[a-zA-Z]+_confirmation/", $key)){
array_splice($model->attributes, array_search($key, array_keys($model->attributes)), 1);
}
}
echo "test"; //This is for debugging if this event is fired or not
return true;
} else {
return false;
}
});
}
}
Now, this is my Post
model :
class Post extends BaseModel {
public static $rules = array(
'body' => 'required',
'user_id' => 'required',
);
}
In this test i'm expecting it to fail. Instead, it passes ! , $post->save()
returns true !
class PostTest extends TestCase {
public function testSavingPost(){
$post = new Post();
$this->assertFalse($post->save());
}
}
When i tried to throw an echo
statement inside the saving
event. It didn't appear, So i understand that my defined saving
event is not invoked. I don't know why.
check out this discussion: https://github.com/laravel/framework/issues/1181
you'll probably need to re-register your events in your tests.
class PostTest extends TestCase {
public function setUp()
{
parent::setUp();
// add this to remove all event listeners
Post::flushEventListeners();
// reboot the static to reattach listeners
Post::boot();
}
public function testSavingPost(){
$post = new Post();
$this->assertFalse($post->save());
}
}
Or, better yet, you should extract the event registration functionality out of the boot function into a public static method:
class Post extends Model {
protected static boot()
{
parent::boot();
static::registerEventListeners();
}
protected static registerEventListeners()
{
static::saving(...);
static::creating(...);
...etc.
}
}
And then call Post::flushEventListeners(); Post::registerEventListeners(); in the setUp() test method.
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