How to login for tests with Devise Authentication
- Berkay Ülke
- 16 Ağu 2019
- 1 dakikada okunur
Majority of your tests will require a test user to login in and log out. For avoiding errors in your log in process and keeping in short, there is a login_as method in Devise. To use this you need to include Devise's Integration Helper in either in your test_helper or test class.

To log in, you need a user instance, and using your existence fixtures will do the trick.
Depending on your project, create your users with proper attributes and use them in your tests

And finally use login_as with a user instance and define your scope if needed. Default value of scope is user, if you're using something else you should define it here. In the following example scope isn't necessary.
Don't forget that this is independent from your test. You can do this both on unit and system tests but you shouldn't consider this as a test. Imagine it like preparing your session, you don't test anything here.
If you're using FactoryBot following line will work fine as well.

For more: https://github.com/plataformatec/devise/wiki/How-To:-Test-with-Capybara
About Devise: https://github.com/plataformatec/devise
Why use scope: https://stackoverflow.com/questions/27264461/gem-warden-why-do-i-need-scope-in-login-as-helper
Kommentare