Testing Laravel Applications with CircleCI & Dusk

I recently started a new project and wanted to give Laravel’s new test framework Dusk a try. Locally, this was quick to do and it worked first time – however when I then connected up CircleCI I needed to do a little extra work to get up and running. In short, the version of Google Chrome needs updating to a newer version and then things should be running well.

Firstly, make sure you’re up and running locally and your tests are passing (that’s half the work done, right?). You should have output similar to:

So, we’re all good at this point. Next, get your circle.yml file looking something like the following:

 

This will make sure you’re using PHP 7.1, start the site running in the background and allow dusk to run. You’ll need to make sure that the APP_URL value in your .env.testing file is pointing to 127.0.0.1. In the example above, we’re making sure that CircleCI adds an entry to /etc/hosts for ‘testing’.

Providing your tests now work, you’ll have a big green bar in CircleCI.

Laravel & Lumen: Return Correct Error Responses for Requests

I’ve seen a few pieces of API code dotted around the web recently where people have written simple JSON APIs but their error handling still returns HTML instead of JSON for 404 errors and the likes. This is pretty simple to solve with Laravel or Lumen and easily testable too. The cleanest way I’ve seen of handling this was written by Paul Redmond in his book ‘Writing APIs with Lumen’ which you can purchase on Leanpub.

In your error handler, typically located at app/Exceptions/Handler.php, you’ll need to add a check for wantsJson() on the Request object, like this:

Pretty simple and effective, you can handle more cases within your handler as well, but that’s enough to illustrate the idea. You can test the above is working by using something similar to this test:

A quick and simple tip, but one that seems to be overlooked often.