-->

How to test SessionsController for OmniAuth with M

2019-07-22 02:55发布

问题:

I'm trying to test my facebook login code with Minitest, but it's not going well.

When I try get :auth, 'provider' => 'facebook' in test, test returns undefined method '[]' for nil:NilClass, and if I try get :new it passes, but auth is not called.

How can I successfully get redirected to auth with omniauth?

Here's my source code.

test/controllers/sessions_controller_test.rb

require 'test_helper'

class SessionsControllerTest < ActionController::TestCase

    test '#signup_success' do
        OmniAuth.config.test_mode = true
        OmniAuth.config.mock_auth[:facebook] = OmniAuth::AuthHash.new({
            'provider' => 'facebook',
            'uid' => '123451234512345',
            'info' => {'email' => 'testuser@testmail.com', 'name' => 'test', 'image' => ''}
        })
        request.env['omniauth.env'] = OmniAuth.config.mock_auth[:facebook]

        get :auth
    end
end

app/controllers/sessions_controller.rb

class SessionsController < ApplicationController
    def auth
        if(env['omniauth.params']['type'] == 'signin')
            if User.find_by(uid: env['omniauth.auth'].uid)
                flash[:alert] = "Already registered"
                redirect_to :back
            else
                user = User.omniauth(env['omniauth.auth'])
                if user.save
                    session[:user_id] = user.uid
                    redirect_to root_url
                else
                    flash[:alert]="Failed to Signin"
                    redirect_to :back
                end
            end
        elsif(env['omniauth.params']['type'] == 'login')
            if User.find_by(uid: env['omniauth.auth'].uid)
                session[:user_id] = env['omniauth.auth'].uid
                redirect_to root_url
            else
                flash[:alert] = "Not registered"
                redirect_to :back
            end
        else
            redirect_to root_url
        end
    end

    def find
        redirect_to '/auth/facebook?type=login'
    end

    def new
        redirect_to '/auth/facebook?type=signin'
    end

    def destroy
        session[:user_id] = nil
        redirect_to root_url
    end
end

回答1:

I think you might just need to use request.env[...] instead of env[...] in SessionsController#auth.