Testing for the Presence of Plugs
Learn how to write tests for the presence of plugs.
We'll cover the following
Defining the test for the presence of plugs
While any basic plugs that we write should be unit-tested, we need to add tests to our test suite to assert that they’re called on every endpoint that’s in the pipeline that includes them. While every Plug is different, in our use case both are run before the controller in the call stack. We only need to test for when things aren’t right. That means that testing multiple endpoints for the presence of the same Plug(s) will start to look a little repetitive because the setup (if it exists) and the assertions will be nearly identical. Often only the endpoint will change. We’ll add two tests to assert the presence of our two plugs.
In the router lib/not_skull_web/router.ex
, our update endpoint is in a pipeline that contains our two custom plugs:
ValidateJWT
MatchJWTUserId
The first Plug, ValidateJWT
, decodes the JWT and makes sure that it’s valid. If it is valid, the Plug takes the user’s ID from the JWT and adds it into the incoming params. If the Plug doesn’t detect a valid JWT, it halts the call stack, returning an HTTP status code of 401 (“Unauthenticated”) and a simple JSON response with a descriptive error.
Get hands-on with 1200+ tech skills courses.