Test after_authentication for Warden implementation

298 Views Asked by At

I've a custom workflow after authentication and I would like to test it.

On initialiser I got something like

Warden::Manager.after_authentication do |user, auth, _opts|
  next unless user.ban?

  auth.logout

  throw(:warden, :message => "You're currently ban. Impossible to connect")
end

I think it's read the whole documentation without finding a correct way to test it. Any idea?

1

There are 1 best solutions below

0
brcebn On

I finally found a way. Not that obvious. Let me share it with you.

According to the source warden/hooks.rb#L71-L78

after_authentication is just a wrapper to after_set_user, which is only invoked when the user is set through the authentication path. The options and yielded arguments are the same as in after_set_user.

So here is my workaround.

describe Warden::Manager do
  describe '#after_authentication' do
    # add here the name of your config file, it's very important
    let(:intializer_file_location) { 'config/initializers/warden.rb' }

    subject do
      after_authentication_proc.call(user, double_auth, opts)
    end

    let(:after_authentication_proc) do
      p, _options = described_class._after_set_user.find do |p, opts|
        opts[:event] == :authentication &&
          p.source_location.first.include?(intializer_file_location)
      end
      p
    end

    let(:user) { create(:user) }
    let(:opts) { {} }
    let(:double_auth) { double(:double_auth) }

    it 'does nothing' do
      expect(subject).to be_nil
    end
  end
end

Enjoy testing!