<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: James LaChance</title>
    <description>The latest articles on DEV Community by James LaChance (@fatboyxpc).</description>
    <link>https://dev.to/fatboyxpc</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F84232%2F0b04bf15-b84c-4f79-9471-52f1c536275d.jpeg</url>
      <title>DEV Community: James LaChance</title>
      <link>https://dev.to/fatboyxpc</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/fatboyxpc"/>
    <language>en</language>
    <item>
      <title>Laravel Testing Woes: Token Mismatch</title>
      <dc:creator>James LaChance</dc:creator>
      <pubDate>Fri, 13 Jul 2018 20:07:04 +0000</pubDate>
      <link>https://dev.to/fatboyxpc/laravel-testing-woes-token-mismatch-28pd</link>
      <guid>https://dev.to/fatboyxpc/laravel-testing-woes-token-mismatch-28pd</guid>
      <description>&lt;p&gt;Laravel has an incredible amount of testing utilities built right in. Anybody that knows me (or that has read my past articles) knows that I believe one of the best parts of Laravel is how much work has been put into testing integrations. Regardless of your opinions about Laravel, check out their &lt;a href="https://laravel.com/docs/5.6/testing"&gt;testing documentation&lt;/a&gt; (make sure to look at the side navigation for the other links), it really is marvelous.&lt;/p&gt;

&lt;p&gt;The natural place to start with testing is with &lt;a href="https://laravel.com/docs/5.6/http-tests"&gt;HTTP tests&lt;/a&gt;, and Laravel calls these “Feature Tests”. For the uninitiated, Feature Tests make a mock HTTP request to your application and allow you to make assertions against the response.&lt;/p&gt;

&lt;p&gt;Note: if you’re already familiar with this issue, and only interested in the path to troubleshooting it, feel free to skip ahead.&lt;/p&gt;

&lt;h3&gt;
  
  
  The Situation
&lt;/h3&gt;

&lt;p&gt;Every now and then I find myself helping somebody who can’t seem to get Feature Tests working outside of a basic GET request. While that’s great, it’s probably pretty important to make POST/PUT/DELETE requests as well, right?&lt;/p&gt;

&lt;p&gt;Just for clarification, let’s write a simple HTTP test that makes a POST request:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight php"&gt;&lt;code&gt;&lt;span class="c1"&gt;// routes/web.php:&lt;/span&gt;
&lt;span class="nc"&gt;Route&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="nf"&gt;post&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;'/'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="s1"&gt;'foo'&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;});&lt;/span&gt;

&lt;span class="c1"&gt;// tests/Feature/ExampleTest.php:&lt;/span&gt;
&lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="n"&gt;testFoo&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
&lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="nv"&gt;$response&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;post&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;'/'&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
    &lt;span class="nv"&gt;$response&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;assertStatus&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;200&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If you created a brand new Laravel application this test would absolutely pass; unfortunately, people often start writing tests at different points through an application’s development cycle, and sometimes this test fails. In this particular case, I’m going to talk about this test specific failure:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;1) Tests\Feature\ExampleTest::testFoo
Expected status code 200 but received 419.
Failed asserting that false is true.
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Okay, I’ll admit that this is fairly cryptic. What does HTTP status 419 mean? It’s not even in the &lt;a href="https://en.wikipedia.org/wiki/List_of_HTTP_status_codes#4xx_Client_errors"&gt;Wikipedia article&lt;/a&gt;! Fortunately for us, Laravel 5.5 introduced a really cool utility method on the default &lt;code&gt;TestCase&lt;/code&gt; object: &lt;code&gt;withoutExceptionHandling()&lt;/code&gt;. All we have to do is add &lt;code&gt;$this-&amp;gt;withoutExceptionHandling()&lt;/code&gt; at the top of our &lt;code&gt;testFoo()&lt;/code&gt; method and any exception that gets handled by Laravel’s &lt;a href="https://laravel.com/docs/5.6/errors#the-exception-handler"&gt;Exception Handler&lt;/a&gt; will get re-thrown and we’ll see it in our console. If you’d like this behavior in Laravel 5.4 and below, you can see &lt;a href="https://adamwathan.me/2016/01/21/disabling-exception-handling-in-acceptance-tests/"&gt;Adam Wathan’s blog article&lt;/a&gt; which inspired this feature.&lt;/p&gt;

&lt;p&gt;After adding &lt;code&gt;$this-&amp;gt;withoutExceptionHandling()&lt;/code&gt;, we now see this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;1) Tests\Feature\ExampleTest::testFoo
Illuminate\Session\TokenMismatchException:

(omitting the long stack trace)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Sometimes, people go ahead and add a token key and value to their request data to get around this error. Sure, this is a short term solution, but who wants to write that for every request? Lucky for us, this is easy enough to troubleshoot!&lt;/p&gt;

&lt;h3&gt;
  
  
  Troubleshooting
&lt;/h3&gt;

&lt;p&gt;All of the examples will be with Laravel 5.6, as that’s the current version at the time of writing this.&lt;/p&gt;

&lt;p&gt;If we take a look at &lt;a href="https://github.com/laravel/laravel/blob/fa81e36841ee25c3440fc430ed8d6b66c641062b/app/Http/Kernel.php#L30-L38"&gt;HTTP Kernel&lt;/a&gt;’s web group of middleware, we’ll see &lt;code&gt;\App\Http\Middleware\VerifyCsrfToken::class&lt;/code&gt;, which is probably a good place to start! Most projects don’t modify this class, so it will look something like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;?php

namespace App\Http\Middleware;

use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as Middleware;

class VerifyCsrfToken extends Middleware
{
    /**
     * The URIs that should be excluded from CSRF verification.
     *
     * @var array
     */
    protected $except = [
        //
    ];
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If you upgraded from an earlier version of Laravel, it might be slightly different, but the concept will remain the same. Notice how this class is mostly empty? We’ll need to defer to the &lt;a href="https://github.com/laravel/framework/blob/21709c981ee3e2844738bd57155d883ee47b7f06/src/Illuminate/Foundation/Http/Middleware/VerifyCsrfToken.php"&gt;parent class&lt;/a&gt; to see the behavior. Since this class is 167 lines, I’m only going to show the relevant part:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight php"&gt;&lt;code&gt;    &lt;span class="cd"&gt;/**
     * Handle an incoming request.
     *
     * @param \Illuminate\Http\Request $request
     * @param \Closure $next
     * @return mixed
     *
     * @throws \Illuminate\Session\TokenMismatchException
     */&lt;/span&gt;
    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="n"&gt;handle&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$request&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="kt"&gt;Closure&lt;/span&gt; &lt;span class="nv"&gt;$next&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;
            &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;isReading&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$request&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;||&lt;/span&gt;
            &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;runningUnitTests&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="o"&gt;||&lt;/span&gt;
            &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;inExceptArray&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$request&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;||&lt;/span&gt;
            &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;tokensMatch&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$request&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;addCookieToResponse&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$request&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nv"&gt;$next&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$request&lt;/span&gt;&lt;span class="p"&gt;));&lt;/span&gt;
        &lt;span class="p"&gt;}&lt;/span&gt;
        &lt;span class="k"&gt;throw&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;TokenMismatchException&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If you aren’t familiar with &lt;a href="https://laravel.com/docs/5.6/middleware"&gt;Laravel Middleware&lt;/a&gt;, go ahead and give it a read as it’s not too hard to understand. For now, just know that all middleware will call the &lt;code&gt;handle()&lt;/code&gt; method. Honestly, getting this far is probably the scariest part. It’s pretty clear here that &lt;code&gt;$this-&amp;gt;runningUnitTests()&lt;/code&gt; must be failing. But why?! We are definitely running this from inside a test!&lt;/p&gt;

&lt;p&gt;Okay, let’s go down the rabbit hole! Let’s see what &lt;code&gt;runningUnitTests()&lt;/code&gt; looks like:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight php"&gt;&lt;code&gt;    &lt;span class="k"&gt;protected&lt;/span&gt; &lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="n"&gt;runningUnitTests&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
    &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;app&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;runningInConsole&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="o"&gt;&amp;amp;&amp;amp;&lt;/span&gt; &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;app&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;runningUnitTests&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Okay, that’s pretty simple, right? From here, it’s as simple as firing up Xdebug and adding a breakpoint or throwing in a &lt;code&gt;dd()&lt;/code&gt; to check the output of &lt;code&gt;$this-&amp;gt;app-&amp;gt;runningInConsole()&lt;/code&gt; and &lt;code&gt;$this-&amp;gt;app-&amp;gt;runningUnitTests()&lt;/code&gt;. So &lt;a href="https://github.com/laravel/framework/blob/21709c981ee3e2844738bd57155d883ee47b7f06/src/Illuminate/Foundation/Application.php"&gt;another step&lt;/a&gt; down the rabbit hole we go:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight php"&gt;&lt;code&gt;    &lt;span class="cd"&gt;/**
     * Determine if the application is running in the console.
     *
     * @return bool
     */&lt;/span&gt;
    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="n"&gt;runningInConsole&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
    &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nb"&gt;php_sapi_name&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="o"&gt;===&lt;/span&gt; &lt;span class="s1"&gt;'cli'&lt;/span&gt; &lt;span class="o"&gt;||&lt;/span&gt; &lt;span class="nb"&gt;php_sapi_name&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="o"&gt;===&lt;/span&gt; &lt;span class="s1"&gt;'phpdbg'&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;

    &lt;span class="cd"&gt;/**
     * Determine if the application is running unit tests.
     *
     * [@return](http://twitter.com/return) bool
     */&lt;/span&gt;
    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="n"&gt;runningUnitTests&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt;
    &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nv"&gt;$this&lt;/span&gt;&lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s1"&gt;'env'&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="o"&gt;===&lt;/span&gt; &lt;span class="s1"&gt;'testing'&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;While it’s a pretty good bet that &lt;code&gt;runningInConsole()&lt;/code&gt; will return true, it doesn’t hurt to verify. For the purpose of this article, I’m going to assume it does return true and that &lt;code&gt;runningUnitTests()&lt;/code&gt; is failing. Now, the obvious place to look is &lt;code&gt;config/app.php&lt;/code&gt; which has a line specifically for &lt;code&gt;'env' =&amp;gt; env('APP_ENV', 'production')&lt;/code&gt;. It’s very likely that your &lt;code&gt;.env&lt;/code&gt; file has &lt;code&gt;APP_ENV=local&lt;/code&gt;. Well that’s the problem, that says local instead of testing! Well, not so fast. A default installation of Laravel has this line in &lt;code&gt;phpunit.xml&lt;/code&gt;: &lt;code&gt;&amp;lt;env name="APP_ENV" value="testing"/&amp;gt;&lt;/code&gt;. It’s certainly worth verifying that line is present and the value is still set to testing.&lt;/p&gt;

&lt;h3&gt;
  
  
  The Likely Suspects
&lt;/h3&gt;

&lt;p&gt;So what if it isn’t that easy? Everything in &lt;code&gt;phpunit.xml&lt;/code&gt; looks fine, and out of extreme paranoia we changed &lt;code&gt;.env&lt;/code&gt; to have &lt;code&gt;APP_ENV=testing&lt;/code&gt; (just to clarify, you don’t actually need to change that, and probably shouldn’t), but we still see that &lt;code&gt;$this['env']&lt;/code&gt; is not &lt;code&gt;testing&lt;/code&gt;. At this point, you will want to start looking at &lt;code&gt;setUp()&lt;/code&gt; methods, both in the test class you are inside of, and &lt;code&gt;tests/TestCase.php&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;You’ll want to be on the lookout for any of the following:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;code&gt;config(['app.env' =&amp;gt; 'not-testing'])&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;config()-&amp;gt;set('app.env', 'not-testing')&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;Config::set('app.env', 'not-testing')&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;putenv('APP_ENV=not-testing')&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;App::detectEnvironment()&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;App::detectEnvironment()&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Note: &lt;code&gt;detectEnvironment()&lt;/code&gt; will have a callback passed to it. Unless your project was upgraded to Laravel 5 from an earlier version, you likely won’t have to worry about this.&lt;/p&gt;

&lt;p&gt;While you scour through the &lt;code&gt;setUp()&lt;/code&gt; methods, you might want to make sure you always call &lt;code&gt;parent::setUp()&lt;/code&gt; while you are inside of it to prevent other negative side effects. It’s also worth looking at the &lt;code&gt;createApplication()&lt;/code&gt; function as well (which was moved to a trait in Laravel 5.4 and above).&lt;/p&gt;

&lt;p&gt;If you still come up empty handed, it’s probably worth doing a search in the entire &lt;code&gt;tests&lt;/code&gt; directory for the value that you see in &lt;code&gt;$this['env']&lt;/code&gt;, and/or checking any sort of Vagrant/Homestad/Docker configuration files you might have.&lt;/p&gt;

&lt;p&gt;While something changed in a test file somewhere is the likely culprit, it’s worth nothing that somebody could be particularly evil and change the environment in the application’s/request lifecycle before the middleware. If somebody were to have fun inside &lt;code&gt;bootstrap/app.php&lt;/code&gt; or even a middleware that is loaded before &lt;code&gt;VerifyCsrfToken&lt;/code&gt;. The HTTP kernel discussed earlier has a &lt;a href="https://github.com/laravel/framework/blob/8af242bd8cc683acfc8ea43be076d8f5b9249606/src/Illuminate/Foundation/Http/Kernel.php#L73"&gt;middleware priority&lt;/a&gt; instance variable that can be overridden.&lt;/p&gt;

&lt;p&gt;This article ended up being a bit longer than I initially expected, but hopefully this gives you more confidence to look through Laravel’s source code on your own, it really isn’t that scary!&lt;/p&gt;

</description>
      <category>laravel</category>
    </item>
  </channel>
</rss>
