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');
}
This worked for me:
And from there you can check the contents of the message box for whatever error you might want verify.
So looking at how
assertViewHas
is implemented HERE it looks like, what the method does, is access the view's data after this call:In your code, the line:
essentially returns the same thing as the line above it, namely a
\Illuminate\Http\Response
(which extends the symfony component\HttpFoundation\Response
)So, inside the
assertViewHas
function it looks like laravel accesses the data using$response->$key
, so I would try to access theclients
and 'content' variables through the$response
object.If that doesn't work try searching around the
TestCase
file in the Laravel framework ... I'm sure the answer is in there somewhere. Also try to dump the$response
object and see what it looks like, there should be some clues there.The first thing I would try, though, is accessing your data through the
$response
object.You can access data in the response and it can be checked..
I managed it by doing it in a messy way. I used
assertViewHas
: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.
So to get a value from the $data object I simply use
$user = $this->getResponseData($response, 'user');
Inside a test case use:
$data = $this->response->getOriginalContent()->getData();
Example:
Example dumping data so you can see what in data(array) passed to view:
Should get something back like what's in image: