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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With