janko / rodauth-rails

Rails integration for Rodauth authentication framework
https://github.com/jeremyevans/rodauth
MIT License
565 stars 40 forks source link

Problem with login integration test helper #233

Closed woller closed 9 months ago

woller commented 9 months ago

I ran into a problem, when I tried to implement a login test helper. Even though the login flow works perfectly in development (thanks for that, by the way 🙂), I cannot make it work during testing.

ENV["RAILS_ENV"] ||= "test"
require_relative "../config/environment"
require "rails/test_help"

class ActiveSupport::TestCase
  # Run tests in parallel with specified workers
  parallelize(workers: :number_of_processors)

  # Setup all fixtures in test/fixtures/*.yml for all tests in alphabetical order.
  fixtures :all

  # Add more helper methods to be used by all tests here...
  def login(account)
    post "/login", as: :json, params: {login: account.email, password: "password"}
  end

  def logout
    post "/logout", as: :json, headers: {"Authorization" => headers["Authorization"]}
  end
end

I've tried omitting as: :json without any effect.

The test I am writing is simple:

require "test_helper"

class AccountsControllerTest < ActionDispatch::IntegrationTest
  let(:account) { accounts(:one) }

  before do
    login account
  end

  describe "#update" do
    it "updates the account" do
      assert_changes -> { account.reload.username }, to: "new_username" do
        patch account_url, params: {account: {username: "new_username"}}
      end
    end
  end
end

I'm using the account fixture generated by the engine without any modifications:

# Read about fixtures at https://api.rubyonrails.org/classes/ActiveRecord/FixtureSet.html
one:
  email: freddie@queen.com
  password_hash: <%= RodauthMain.allocate.password_hash("password") %>
  status: verified

two:
  email: brian@queen.com
  password_hash: <%= RodauthMain.allocate.password_hash("password") %>
  status: verified

I don't really know how to debug this, as the only response I get back from the login-method is 401 as an integer. I am on rodauth-rails 1.11.0 and rails 7.0.8 in a fresh Rails app. I even tried spinning up a new rails app (available here) and was able to reproduce the error.

janko commented 9 months ago

The login param name was changed from login to email in newer rodauth-rails versions, to be more in line with people's expectations from other Rails-based authentication frameworks. I forgot to update the wiki page, I will do that shortly.

woller commented 9 months ago

That was the issue. I really should have spotted that in the server logs 🙂 Thanks so much!