Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get view data during unit testing in Laravel

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 = \Models\User::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 = Models\User::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');

}
like image 672
Claire Avatar asked Jan 15 '14 13:01

Claire


People also ask

What is refreshDatabase in Laravel?

refreshDatabase() Define hooks to migrate the database before and after each test. bool. usingInMemoryDatabase() Determine if an in-memory database is being used.

What is PHPUnit Laravel?

Use Laravel Unit Testing to Avoid Project-Wrecking Mistakes. Pardeep Kumar. 7 Min Read. PHPUnit is one of the most well known and highly optimized unit testing packages of PHP. It is a top choice of many developers for rectifying different developmental loopholes of the application.

What is PHPUnit?

PHPUnit is a unit testing framework for the PHP programming language. It is an instance of the xUnit design for unit testing systems that began with SUnit and became popular with JUnit. Even a small software development project usually takes hours of hard work.


1 Answers

TL;DR; Try $data = $response->getOriginalContent()->getData();


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();

    $data = $content->getData();

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

}

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

like image 83
Claire Avatar answered Oct 19 '22 11:10

Claire