2014-01-10 161 views
3

說我有兩個模型,從Eloquent延伸,它們相互關聯。我可以嘲笑關係嗎?laravel 4嘲笑模擬模型關係

即:

class Track extends Eloquent { 
    public function courses() 
    { 
     return $this->hasMany('Course'); 
    } 
} 

class Course extends Eloquent { 
    public function track() 
    { 
     return $this->belongsTo('Track'); 
    } 
} 

在MyTest的,我想通過調用跟蹤屬性,而不是賽道實例(我不創造過程的模擬,並返回軌道,的一個實例要查詢生成器

use \Mockery as m; 

class MyTest extends TestCase { 
    public function setUp() 
    { 
     $track = new Track(array('title' => 'foo')); 
     $course = m::mock('Course[track]', array('track' => $track)); 

     $track = $course->track // <-- This should return my track object 
    } 
} 

回答

7

由於賽道是一個屬性,而不是一個方法,創造了模擬時,你會需要重寫setAttributegetAttribute方法s的模型。下面是一個解決方案,可以讓你設置該屬性的期望,你正在尋找:

$track = new Track(array('title' => 'foo')); 
$course = m::mock('Course[setAttribute,getAttribute]'); 
// You don't really care what's returned from setAttribute 
$course->shouldReceive('setAttribute'); 
// But tell getAttribute to return $track whenever 'track' is passed in 
$course->shouldReceive('getAttribute')->with('track')->andReturn($track); 

嘲諷Course對象時,你並不需要指定track方法,除非你也想測試代碼依賴查詢生成器。如果是這種情況,那麼你可以嘲笑這樣的track方法:

// This is just a bare mock object that will return your track back 
// whenever you ask for anything. Replace 'get' with whatever method 
// your code uses to access the relationship (e.g. 'first') 
$relationship = m::mock(); 
$relationship->shouldReceive('get')->andReturn([ $track ]); 

$course = m::mock('Course[track]'); 
$course->shouldReceive('track')->andReturn($relationship);