Integration tests with minitest, Sorcery and Rails 7

Jorge Alvarez - Aug 16 '23 - - Dev Community

The example app at https://github.com/Sorcery/sorcery-example-app/tree/master does not work for integration tests. Here is a configuration that helps you log in using Sorcery.

Edit your test_helper.rb file

class ActionController::TestCase
  include Sorcery::TestHelpers::Rails::Controller
end

class ActionDispatch::IntegrationTest
  include Sorcery::TestHelpers::Rails::Integration
end

module Sorcery
  module TestHelpers
    module Rails
      # Passwords? Where we are going, we don't need passwords.
      def login_user_post(email, route = nil)
        password = 'top-secret'
        user ||= @user
        user.password = password
        user.password_confirmation = password
        user.save!
        where = route.presence || user_sessions_path
        send(:post, where, params: { email:, password: })
      end
    end
  end
end
Enter fullscreen mode Exit fullscreen mode

And now in your integration files you can log in using the method login_user_post with a user's email.

tests/integration/admin/settings_test.rb

class Admin::SettingsTest < ActionDispatch::IntegrationTest
  class NotManager < Admin::SettingsTest
    def setup
      @user = user(:user)
      login_user_post @user.email
    end

    test 'can not access admin area' do
      get admin_settings_url

      assert_response :redirect
    end
  end

  class Manager < Admin::SettingsTest
    def setup
      @user = user(:manager)
      login_user_post @user.email
    end

    test 'can access admin area' do
      get admin_settings_url

      assert_response :success
    end
  end
end
Enter fullscreen mode Exit fullscreen mode
. . . . . . . . . . . . . . . .