【问题标题】:How to test SessionsController for OmniAuth with Minitest如何使用 Minitest 为 OmniAuth 测试 SessionsController
【发布时间】:2015-05-05 08:33:00
【问题描述】:

我正在尝试使用 Minitest 测试我的 facebook 登录代码,但进展不顺利。

当我在测试中尝试get :auth, 'provider' => 'facebook' 时,测试返回undefined method '[]' for nil:NilClass,如果我尝试get :new,它会通过,但不会调用身份验证。

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

这是我的源代码。

测试/控制器/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

【问题讨论】:

    标签: ruby-on-rails facebook omniauth minitest


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2018-06-20
      • 1970-01-01
      • 1970-01-01
      • 2023-03-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多