I have an API that requires authentication, created using Rails 5. The basic flow of the authentication is that the user performs a login with a username/password in a Base64-encoded Authorization: Basic
header, along with an API key. This is then exchanged for an authorization token, which is recorded in the user database table and is good for some period of time. Subsequent API calls require this token in an Authorization: Bearer
header.
The problem I'm having is that, when I try to test a controller that requires authentication, I'm having to go through this dance of logging the user in (to ensure that the auth_token
is in the test database table, since this might be the first test that's being run, etc...) This is complicated, because, if, for example, I am testing a controller called RecipesController
, and my authentication lives in AuthController
, I need to switch controllers in order to perform the login stuff.
I've successfully done this in the past in spec_helper.rb
using something like:
def login username, password
current_controller = @controller
... setup login call ...
post :login
@controller = current_controller
... return auth token ...
end
However, as I've realized in Why are parameters not being passed within my test in Rails 5?, I believe this is messing up my test request, and parameters are being lost as a result.
This seems like a pretty straightforward pattern to use, though, so I'm wondering how to test it? I'd actually prefer to test the authentication separately, and just pass in a mocked user object, but I'm not sure how to do this, since I'm not as familiar with Rails as I'd like to be.
Aucun commentaire:
Enregistrer un commentaire