In Laravel 5, why is Request::root() different when called during phpunit test?

kurt165749

I defined a test which tests the creation of a user. The controller is set to redirect back to the same page on error (using validation through a generated App\Http\Requests\Request). This works correctly when manually clicking in a browser, but fails during a test. Instead of being redirected to:

http://localhost/account/create

The test redirects to (missing a slash):

http://localhostaccount/create

Neither of these urls are what I have setup in the .htaccess or in the $url variable in config/app.php. Which is (On OSX Yosemite):

http://~username/laravel_projects/projectname/public

I finally pinpointed the issue to have something to do with how the result of Request::root() is generated. Making a call to this outside of a test results in the expected value defined in .htaccess and $url. Inside the test it results in:

http://localhost

What configuration needs to change in order to get this function to return the correct value in both contexts?

I should also mention I made the painful upgrade from Laravel 4 to the current version 5.0.27.

****** UPDATE *******

I was able to figure out an acceptable solution/workaround to this issue!

In Laravel 5, FormRequests were introduced to help move validation logic out of controllers. Once a request is mapped to the controller, if a FormRequest (or just Request) is specified, this is executed before hitting the controller action.

This FormRequest by default handles the response if the validation fails. It attempts to construct a redirect based on the route you posted the form data to. In my case, possibly related to an error of mine updating from Laravel 4 to 5, this default redirect was being constructed incorrectly. The Laravel System code for handling the response looks like this:

 /**
 * Get the proper failed validation response for the request.
 *
 * @param  array  $errors
 * @return \Symfony\Component\HttpFoundation\Response
 */
public function response(array $errors)
{
    if ($this->ajax() || $this->wantsJson())
    {
        return new JsonResponse($errors, 422);
    }
    return $this->redirector->to($this->getRedirectUrl())
                                    ->withInput($this->except($this->dontFlash))
                                    ->withErrors($errors, $this->errorBag);
}

Notice how the returned redirect is NOT the same as calling Redirect::route('some_route'). You can override this response function by including use Response in your Request class.

After using Redirect::route() to create the redirect, the logic in my tests passed with the expected results. Here is my Request code that worked:

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;
use App\Http\Requests\Request;
use Response;

class AccountRequest extends FormRequest {

    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
                  'email' => 'required|max:50|email|unique:users',
                  'password' => 'required|min:6',
                  'password_confirmation' => 'required|same:password'

                ];
    }

  public function response(array $errors){
    return \Redirect::route('account_create');
  }

}

The important part is that I called Redirect::route instead of letting the default response code execute.

kurt165749

Override the response function in the FormRequest validation handler to force the redirect to be constructed with Redirect::route('named_route') instead of allowing the default redirect.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

PHPUnit: Expectations orders ignored in test when same stubbed method called multiple times with different arguments

From Dev

PHPUnit testing FAILS ONLY when visiting the root page( visit('/') ) in Laravel 5

From Dev

Laravel 5 PHPUnit test fails with getContent() on null

From Dev

Test with PHPUnit Laravel 5 controller with database (Mock?)

From Dev

Laravel 5 PHPUnit test json post

From Dev

Test with PHPUnit Laravel 5 controller with database (Mock?)

From Dev

Laravel 5 PHPUnit test fails with getContent() on null

From Dev

Why custom callback not called when yield Request , but parse method called?

From Dev

How to test form request rules in Laravel 5?

From Dev

PHPUnit not working with Laravel 5

From Dev

Hide output during PHPUnit test execution

From Dev

Hide output during PHPUnit test execution

From Dev

PHPUnit test if class methods were called

From Dev

how to test if the correct function is called in phpunit

From Dev

why different file sizes for laravel 5?

From Dev

Laravel Request not found when called within a Controller's function

From Dev

Why is DHCP Request called request

From Dev

Why CreateAsync of AuthenticationTokenProvider Is Called When Request to Exchange RefreshToken Arrives?

From Dev

Phpunit cannot find test, No test executed(Laravel)

From Dev

Why are implicit variables not initialized in Scala when called from unit test?

From Dev

Laravel 5 phpunit is not running tests

From Dev

stuck with phpunit testing in laravel 5

From Dev

Laravel 5: Request data is null when using an Ajax Post Request

From Dev

How to share objects in different test in PHPUnit

From Dev

Laravel 5 Redirect Not Working When Called From An External Class

From Dev

Laravel 5.1 PHPUnit with "use DatabaseMigrations;" Produces Error when Accessing Test DB

From Dev

Python: Why would a function called within a while loop return something different than when called alone?

From Dev

How to test namespaced objects in Laravel 4 with phpunit

From Dev

How to test file upload with laravel and phpunit?

Related Related

  1. 1

    PHPUnit: Expectations orders ignored in test when same stubbed method called multiple times with different arguments

  2. 2

    PHPUnit testing FAILS ONLY when visiting the root page( visit('/') ) in Laravel 5

  3. 3

    Laravel 5 PHPUnit test fails with getContent() on null

  4. 4

    Test with PHPUnit Laravel 5 controller with database (Mock?)

  5. 5

    Laravel 5 PHPUnit test json post

  6. 6

    Test with PHPUnit Laravel 5 controller with database (Mock?)

  7. 7

    Laravel 5 PHPUnit test fails with getContent() on null

  8. 8

    Why custom callback not called when yield Request , but parse method called?

  9. 9

    How to test form request rules in Laravel 5?

  10. 10

    PHPUnit not working with Laravel 5

  11. 11

    Hide output during PHPUnit test execution

  12. 12

    Hide output during PHPUnit test execution

  13. 13

    PHPUnit test if class methods were called

  14. 14

    how to test if the correct function is called in phpunit

  15. 15

    why different file sizes for laravel 5?

  16. 16

    Laravel Request not found when called within a Controller's function

  17. 17

    Why is DHCP Request called request

  18. 18

    Why CreateAsync of AuthenticationTokenProvider Is Called When Request to Exchange RefreshToken Arrives?

  19. 19

    Phpunit cannot find test, No test executed(Laravel)

  20. 20

    Why are implicit variables not initialized in Scala when called from unit test?

  21. 21

    Laravel 5 phpunit is not running tests

  22. 22

    stuck with phpunit testing in laravel 5

  23. 23

    Laravel 5: Request data is null when using an Ajax Post Request

  24. 24

    How to share objects in different test in PHPUnit

  25. 25

    Laravel 5 Redirect Not Working When Called From An External Class

  26. 26

    Laravel 5.1 PHPUnit with "use DatabaseMigrations;" Produces Error when Accessing Test DB

  27. 27

    Python: Why would a function called within a while loop return something different than when called alone?

  28. 28

    How to test namespaced objects in Laravel 4 with phpunit

  29. 29

    How to test file upload with laravel and phpunit?

HotTag

Archive