A step-by-step chapter walks through testing Rails 8's built-in authentication generator in a sample Cookbook app built with Minitest. It covers generating authentication, adding user fixtures, writing a current_user helper, testing sign-in and sign-out over integration and system tests, restricting guests to read-only access while allowing signed-in users full CRUD, and setting up session helpers for both integration and system test suites.

38m read timeFrom minitestrails.com
Post cover image
Table of contents
This chapter on the Cookbook appWhy you waited until now #What you will do in this chapter #Scenarios to automate #Generate authentication #Change root url for the app #User fixtures #Add a current_user helper #Sign in to the app #Sign-in helper for tests #Sign out of the app #Guest can only read recipes #Guests browse, recipe modification buttons are shown for signed in users, and the tests prove both.Signed-in users can still change recipes #Reset a forgotten password #Delete the scaffold Recipes controller test #Commit your work #What is next #

Questions this post answers

How do I test Rails 8 built-in authentication with Minitest?

Use the sign_in_as helper for integration tests, which creates a real Session row and sets the signed session_id cookie directly, and a custom sign_in_to_ui_as helper for system tests that visits the sign-in page then injects the signed cookie into the browser. Reserve driving the actual sign-in form for testing the sign-in flow itself; use the cookie-injection helpers for everything else that just needs an existing session. Developers wiring up Rails 8 auth tests can compare approaches like this on daily.dev before writing their own helpers.

What files does the Rails 8 generate authentication command create?

Running bin/rails generate authentication creates app/models/user.rb, session.rb, and current.rb, an Authentication concern in app/controllers/concerns, sessions_controller.rb and passwords_controller.rb, a passwords_mailer, views for sessions and passwords, migrations for users and sessions tables, and a session_test_helper.rb for integration tests, plus a starter users.yml fixture. Rails developers evaluating the built-in generator versus Devise can track this kind of breakdown on daily.dev.

How do I restrict guest users to read-only access in a Rails app using the authentication concern?

Add allow_unauthenticated_access only: %i[index show] to the controller so index and show skip the require_authentication before_action while every other action still requires a session. Wrap New, Edit, Destroy, and Remove buttons in views with an authenticated? check so guests never see controls for actions they cannot perform. Teams designing guest versus signed-in permissions in Rails can dig into patterns like this on daily.dev.

144 Impressions