Tray2's avatar
Level 74

Data found with manual browser test but not with phpunit

I'm building a Media Register where among other thing you can store your books and I ran into an intresting issue.

From the author show view I have a link to the create route. On said route I add the sluggified complete authors name so the url looks like this.

/books/create?author=jordan_robert

So I wrote a test for this looking like so

    /** @test */
    public function it_gets_the_author_from_in_the_query_string_and_populate_the_hidden_author_field()
    {
        $this->withoutExceptionHandling();
        $this->signIn();
        factory(Author::class)->create(['first_name' => 'Robert', 'last_name' => 'Jordan']);

        $response = $this->get('/books/create?author=' . str_slug('jordan-robert'));

        $response->assertSee('value="Jordan, Robert"');
        $response->assertSee('value="1"');
    }

And my create method looks looked like this

   public function create(Request $request)
    {
        $author = '';
        if($request->has('author')) {
            $authorName = explode('-', $request->query('author'));
            $author = Author::where('first_name', $authorName[1])->where('last_name',  $authorName[0])->get();
        }
        $genres = Genre::orderBy('genre')->get();
        $formats = Format::orderBy('format')->get();
        return view('books.create', compact('genres', 'formats', 'author'));
    }

Now this test fails since it does not find the author even though it's created. However when I do this in the browser it works perfectly.

After almost an hour I found the issue. There is a difference in how the code is executed.

When running in the browser the query is case insensitive while when ran from phpunit it's case sensitive.

So I had to add ucFirst to the query like so.

   public function create(Request $request)
    {
        $author = '';
        if($request->has('author')) {
            $authorName = explode('-', $request->query('author'));
            $author = Author::where('first_name', ucFirst($authorName[1]))->where('last_name', ucFirst($authorName[0]))->get();
        }
        $genres = Genre::orderBy('genre')->get();
        $formats = Format::orderBy('format')->get();
        return view('books.create', compact('genres', 'formats', 'author'));
    }

And then it works in both browser and phpunit.

0 likes
1 reply
jlrdw's avatar

Good information to share, the RFC 2616 and later RFC 7230 contains this. But many new to programming don't realize this, so I will definitely book mark this to refer others to as needed.

Thanks for the share.

1 like

Please or to participate in this conversation.