Skip to content

[Docs] Getting Started guide: add instructions to update tests after authentication is added #54382

Open
@miguno

Description

@miguno

Background

The new Getting Started guide of Rails 8 has a chapter on Adding Authentication (with the new v8 authentication generator). What is missing are instructions (or pointers to other docs) for users on how to write tests for controller actions that require authentication. There is no such information in Securing Rails Applications, either.

Expected behavior

When I finish the Getting Started guide, I'm ready to write tests for my first app (possibly by using my local "finished" Getting Started code as the starting point), including any such tests that require authentication.

Actual behavior

When I finish the Getting Started guide, I have no ready-to-use information at hand for "creating tests that require authentication".

What helped me was the answer to the StackOverflow question How to test Controller with sign in user on Rails 8 authentication from Nov 2024.

Example

Here's an example change for how I fixed tests that I manually added (before chapter 11) while going through the new Rails Getting Started guide and that subsequently broke after adding authentication in chapter 11:

diff --git test/controllers/products_controller_test.rb test/controllers/products_controller_test.rb
index 8ff3369..49cd4e2 100644
--- test/controllers/products_controller_test.rb
+++ test/controllers/products_controller_test.rb
@@ -3,6 +3,11 @@
 require "test_helper"

 class ProductsControllerTest < ActionDispatch::IntegrationTest
+  setup do
+    @user = users(:one)
+    sign_in @user
+  end
+
   test "should get index" do
     get products_url
     assert_response :success
@@ -48,4 +53,8 @@ class ProductsControllerTest < ActionDispatch::IntegrationTest
     end
     assert_redirected_to products_url
   end
+
+  private def sign_in(user, password: "password")
+    post session_url, params: { email_address: user.email_address, password: }
+  end
 end

Related

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions