Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test Controller with sign in user on Rails 8 authentication

I just try the new Rails 8 with build in authentication, and have this issue when testing Controller using minitest.

Here is the error after running rails test. Since Rails 8 build in authentication is quite new, after further research I still not sure which steps that I miss.

Failure:
TicketsControllerTest#test_should_get_index [test/controllers/tickets_controller_test.rb:12]:
Expected response to be a <2XX: success>, but was a <302: Found> redirect to <http://www.example.com/session/new>
Response body: 

Here is the simplified code for test/controllers/tickets_controller_test.rb

require "test_helper"

class TicketsControllerTest < ActionDispatch::IntegrationTest
  setup do
    @category = categories(:one)
    @user = users(:one)
    sign_in @user
  end

  test "should get index" do
    get tickets_url
    assert_response :success
  end

  test "should get new" do
    get new_ticket_url
    assert_response :success
  end

  private

  def sign_in(user)
    post new_session_url, params: { email_address: user.email_address, password: "password" }
  end
end

Fixtures test/fixtures/users.yml

<% password_digest = BCrypt::Password.create("password") %>

one:
  email_address: [email protected]
  password_digest: <%= password_digest %>

two:
  email_address: [email protected]
  password_digest: <%= password_digest %>

Dev environment is using .devcontainer with Postgres 16

like image 925
cyberfly Avatar asked Sep 01 '25 03:09

cyberfly


1 Answers

Oops silly me. After further debugging looks like I made a beginner mistake.

On Rails 8 new build in authentication, here is the authentication routes that you can find via rails routes | grep session

| Named Route   | HTTP Verb | Path                         |
|---------------|-----------|------------------------------|
| new_session   | GET       | /session/new(.:format)       |
| edit_session  | GET       | /session/edit(.:format)      |
| session       | GET       | /session(.:format)           |
| session       | PATCH     | /session(.:format)           |
| session       | PUT       | /session(.:format)           |
| session       | DELETE    | /session(.:format)           |
| session       | POST      | /session(.:format)           |

So the mistake is I was using the wrong route new_session_url but the correct answer is session_url. Here is the updated method of sign_in

def sign_in(user)
    post session_url, params: { email_address: user.email_address, password: "password" }
  end

And to made this reuseable, we can move this method into test_helper.rb

like image 90
cyberfly Avatar answered Sep 02 '25 17:09

cyberfly