2013-07-28 42 views
0

我想測試創建一個追隨者,但是,因爲我打電話驗證::用戶() - > ID我得到的錯誤「試圖獲得非對象的屬性」。目前,我一直在建設一個輸入數組,當我運行create方法驗證是從BaseModel引導方法所觸發。有沒有辦法,我應該嘲笑$輸入數組或我應該做的創建方法驗證在我的倉庫?laravel可測試存儲方法與驗證在basemodel

<?php 

class FollowersTest extends TestCase { 

public function setUp() 
{ 
    parent::setUp(); 

    $this->mock = $this->mock('Convoconnect\Storage\Follower\FollowerRepository'); 
} 

public function mock($class) 
{ 
    $mock = Mockery::mock($class); 

    $this->app->instance($class, $mock); 

    return $mock; 
} 

public function tearDown() 
{ 
    Mockery::close(); 
} 

/** 
* Test Store success 
*/ 
public function testStoreSuccess() 
{ 
    $input = [ 
    'user_id' => 1, 
    'follower_id' => 4, 
    ]; 

    $this->mock 
     ->shouldReceive('create') 
     ->once(); 

    $this->call('POST', 'followers', $input); 

    $this->assertRedirectedToRoute('followers.index'); 
} 
} 



<?php 

use Convoconnect\Storage\Follower\FollowerRepository as Follower; 

class FollowersController extends BaseController { 

/** 
* Follower Repository 
* 
* @var Follower 
*/ 
protected $follower; 

public function __construct(Follower $follower) { 
    $this->follower = $follower; 
} 

public function store() { 

    $input = [ 
     'user_id' => Auth::user()->id, 
     'follower_id' => Input::get('follower_id'), 
    ]; 

    $follower = $this->follower->create($input); 

    if($follower->save()) return Redirect::route('followers.index'); 

    return Redirect::back() 
     ->withInput() 
     ->withErrors($follower->errors); 
} 
} 

回答

1

你可以嘲笑Validator行爲:

Validator::shouldReceive('make') 
    ->once() 
    ->andReturn(Mockery::mock(array('fails' => true))); 

有一個關於測試控制器了很多有用的信息,this Nettuts article。傑弗里路的書,Laravel Testing Decoded,也非常值得一看。

+0

我的問題是我的測試失敗,因爲我調用Auth :: user() - > id來建立我的輸入,所以我得到的錯誤「試圖獲得非對象的屬性」 –

+0

Laravel包括[測試輔助方法](http://laravel.com/docs/testing#helper-methods)來設置當前已驗證用戶。 –