如何在 Laravel 单元测试期间获取视图数据

2022-01-08 00:00:00 php laravel laravel-4 phpunit

我想检查控制器函数中赋予视图的数组是否具有某些键值对.如何使用 phpunit 测试来做到这一点?

I would like to check the array given to a view in a controller function has certain key value pairs. How do I do this using phpunit testing?

//my controller I am testing


public function getEdit ($user_id)
{
    $this->data['user'] = $user = ModelsUser::find($user_id);

    $this->data['page_title'] = "Users | Edit";

    $this->data['clients'] = $user->account()->firstOrFail()->clients()->lists('name', 'id');

    $this->layout->with($this->data);

    $this->layout->content = View::make('user/edit', $this->data);
}

//my test
public function testPostEdit (){

    $user = ModelsUser::find(parent::ACCOUNT_1_USER_1);

    $this->be($user);

    $response = $this->call('GET', 'user/edit/'.parent::ACCOUNT_1_USER_1);   

    //clients is an array.  I want to get this 
    //array and use $this->assetArrayContains() or something
    $this->assertViewHas('clients');

    $this->assertViewHas('content');

}

推荐答案

我找到了更好的方法.我在 TestCase 中写了一个函数,它从视图数据中返回我想要的数组.

I found a better way to do it. I wrote a function in the TestCase which returns the array I want from the view data.

protected function getResponseData($response, $key){

    $content = $response->getOriginalContent();

    $content = $content->getData();

   return $content[$key]->all();

}

所以要从 $data 对象中获取值,我只需使用 $user = $this->getResponseData($response, 'user');

So to get a value from the $data object I simply use $user = $this->getResponseData($response, 'user');

相关文章