7

I am testing a controller method and I am accessing a route in a test.

Then I would like to make sure that the correct model was returned in the view and was loaded with all of the correct relationships.

I know that I can do this:

$this->assertViewHas("content");

But can how can I verify that the content model that was returned into the view has the correct, for example, category? i.e. how can I get the content model object and then do something like

$this->assertEquals($content->category->name, "category 1");

?

9
  • Why not grab the actual controller method and test to make sure it has the right info? Commented Mar 13, 2017 at 21:36
  • 1
    Even if I do grab the actual controller, it returns a View. How do I access the Content model object from the view? I guess that would be a solution to my question, but I don't know the answer. Commented Mar 13, 2017 at 21:43
  • Checking the source code, it appears you can use something like ->assertViewHas($key, $value). Commented Mar 13, 2017 at 21:59
  • @CalebAnthony Yes I have seen that but maybe I am getting confused. I know I can do ->assertViewHas('content', $value) but what I want to do is ->assertViewHas('content->category', $value) and this returns null (I think because trying to access the View's 'content' attribute returns an Eloquent object and not a Model. I am not exactly sure. Or because the view doesn't have a 'content->category' attribute. But in any case, i haven't been able to get it to do what I want. Commented Mar 13, 2017 at 22:24
  • 1
    Possible duplicate of How to get view data during unit testing in Laravel Commented Jun 6, 2017 at 13:02

4 Answers 4

8

You can get your content from the response like this:

$content = $response->getOriginalContent()->getData()['content'];

getData() returns the data sent to the view as an array.

Sign up to request clarification or add additional context in comments.

Comments

3

Use assertSee():

$response->assertSee("category 1");

Comments

3

You can use the following to get the array that's passed to the view:

$response->original->getData()

This comes from Illuminate/Http/ResponseTrait (link to docs).

2 Comments

This is just a property shortcut to Vito Meuli's 2017 answer.
Yup I think it reads cleaner so wanted to share with the community
1

You can use

$your_desired_data = $response->assertSee('var_tag');

and if it's an array of data you can access its data by:

$first_name = $your_desired_data['first_name'];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.