Laravel 4 controller tests - ErrorException after too many $this->call() - why?

可紊 提交于 2019-12-05 12:34:53
fideloper

Probable Solution:

Use $this->client->restart() to start a new request.

Explanation/Detail:

OK so, here's the rabbit hole :D

  1. Laravel TestCase extends Illuminate\Foundation\Testing\TestCase
  2. Illuminate\Foundation\Testing\TestCase uses Illuminate\Foundation\Testing\Client to make the fake requests.
  3. Illuminate\Foundation\Testing\Client extends Symfony\Component\HttpKernel\Client
  4. Symfony\Component\HttpKernel\Client extends abstract class Symfony\Component\BrowserKit\ Client
  5. Abstract class Symfony\Component\BrowserKit\ Client has a method restart()

So, I believe in your case (I haven't personally tested this), you should be able to do the following:

/**
 * When the user skips questions they have not yet answered, the user 
 * should be redirected back to the first unanswered question.
 *
 * @return void
 */
public function testDiscoverSkipQuestions()
{
    // Get the first question.
    $domCrawler = $this->client->request('GET', 'style/discover');

    // Answer the first question
    $form = $domCrawler->selectButton("Next »")->form();
    $form['question_1'] = 'A:0';
    $response = $this->client->submit($form);
    $this->assertRedirectedTo('style/discover/2');

    // ******** Restart for new request ********
    $this->client->restart();

    // Get the 5th question.
    $this->call('GET', 'style/discover/5');
    // ******** SHOULD NOW WORK - call() is a proxy to $this->client->request(); ********

    // Expect to be redirected to the 2nd question.
    $this->assertRedirectedTo('style/discover/2');
    $this->assertSessionHas('attention');
}

Note that the call() method is a proxy to using $this->client->request()

Hope that helps! Don't be afraid to dig into code inheritances to see if a convenience method exists to do what you need - changes are it often already exists :D

Improvement(?)

Note that these tests might lean more towards "integration tests" rather than "unit tests". Integration tests may be a better fit when used with continuous integration frameworks. See this question for some more info.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!