DEV Community

Discussion on: Tips for testing: Authentication with devise_token_auth in Rails API

Collapse
 
philnash profile image
Phil Nash

I'm a little concerned for the time your tests will take to run. If you have to make two requests, one of which creates a user, before every authenticated test then the time is going to grow quickly as you add tests.

I recalled that devise on its own provides helper methods when you want to test, so I wondered what devise_token_auth provided. It turns out that when you use devise_token_auth with a resource you get one new method create_new_auth_token which returns all the values you need.

This means you can use existing users in your tests (if you are using fixtures) or you could use a factory to create a user. This would avoid the two calls to controllers before each test. Your setup function could look like this instead:

def setup
  test_user_options = { email: 'user@test.com', password: 'testuser' }
  user = create_user(test_user_options) # factory to create user
  request.headers.merge! user.create_new_auth_token
end
Enter fullscreen mode Exit fullscreen mode

I got the last line from the devise_token_auth testing documentation. With this version, you don't need the AuthorizationHelper.

What do you think? Could this simplify your tests and make them run quicker?

Collapse
 
risafj profile image
Risa Fujii

Thank you for your comment! Sorry for the late response - your point seems very valid and I will definitely look into it.