How to test SessionsController for OmniAuth with Minitest

☆樱花仙子☆ 提交于 2019-12-11 02:44:09

问题


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.



来源:https://stackoverflow.com/questions/30047905/how-to-test-sessionscontroller-for-omniauth-with-minitest

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!