如何使用Minitest测试SessionsController for OmniAuth [英] How to test SessionsController for OmniAuth with Minitest

查看:70
本文介绍了如何使用Minitest测试SessionsController for OmniAuth的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试用Minitest测试我的Facebook登录代码,但是效果不佳.

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

当我在测试中尝试get :auth, 'provider' => 'facebook'时,测试返回undefined method '[]' for nil:NilClass,如果我尝试get :new则测试通过,但未调用auth.

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.

如何使用omniauth成功重定向到auth?

How can I successfully get redirected to auth with omniauth?

这是我的源代码.

test/controllers/sessions_controller_test.rb

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

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

推荐答案

我认为您可能只需要使用request.env[...]而不是SessionsController#auth中的env[...].

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

这篇关于如何使用Minitest测试SessionsController for OmniAuth的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆