如何编写Rails 4测试以使用omniauth-google-oauth2 gem创建会话?

dav*_*mcd 6 ruby unit-testing ruby-on-rails omniauth ruby-on-rails-4

我正在尝试编写一个测试来创建与omniauth-google-oauth2gem 的会话.我需要传递env["omniauth.auth"]变量post :create吗?也许当我试图这样做时,我做错了.我得到的错误如下所示......

耙测试错误

  1) Error:
SessionsControllerTest#test_should_get_create:
NoMethodError: undefined method `provider' for nil:NilClass
    app/models/user.rb:6:in `from_omniauth'
    app/controllers/sessions_controller.rb:4:in `create'
    test/controllers/sessions_controller_test.rb:13:in `block in <class:SessionsControllerTest>'
Run Code Online (Sandbox Code Playgroud)

以下是我尝试编写测试...

SessionsControllerTest

require 'test_helper'

class SessionsControllerTest < ActionController::TestCase

  setup :prepare_omniauth

  test "should get create" do
    post :create
    redirect_to root_path, notice: "Signed in!"
  end

  test "should get destroy" do
    get :destroy
    assert session[:user_id].blank?, "user_id should no longer exist"
    assert_redirected_to root_path, notice: "Signed out!"
  end

  private

    def prepare_omniauth
      OmniAuth.config.test_mode = true
      OmniAuth.config.mock_auth[:google] = OmniAuth::AuthHash.new({
        :provider => 'google',
        :uid => '123545'
      })
      request.env["omniauth.auth"] = OmniAuth.config.mock_auth[:google]
    end

end
Run Code Online (Sandbox Code Playgroud)

会话控制器

class SessionsController < ApplicationController

  def create
    user = User.from_omniauth(env["omniauth.auth"])
    session[:user_id] = user.id
    redirect_to root_path
  end

  def destroy
    session[:user_id] = nil unless session[:user_id].blank?
    redirect_to root_path
  end

end
Run Code Online (Sandbox Code Playgroud)

用户模型

class User < ActiveRecord::Base

  def self.from_omniauth(auth)
    where(provider: auth.provider, uid: auth.uid).first_or_initialize.tap do |user|
      user.provider = auth.provider
      user.uid = auth.uid
      user.name = auth.info.name
      user.oauth_token = auth.credentials.token
      user.oauth_expires_at = Time.at(auth.credentials.expires_at)
      user.save!
    end
  end

end
Run Code Online (Sandbox Code Playgroud)

akz*_*z92 1

我相信这个博客可以回答您的问题:http://natashatherobot.com/rails-test-omniauth-sessions-controller/

基本上,您需要编辑rails_helper/spec_helper以将Omniauth的测试模式设置为true并创建要在测试中使用的omniauth_hash:

OmniAuth.config.test_mode = true
omniauth_hash = { 'provider' => 'github',
                  'uid' => '12345',
                  'info' => {
                      'name' => 'natasha',
                      'email' => 'hi@natashatherobot.com',
                      'nickname' => 'NatashaTheRobot'
                  },
                  'extra' => {'raw_info' =>
                                  { 'location' => 'San Francisco',
                                    'gravatar_id' => '123456789'
                                  }
                  }
}

OmniAuth.config.add_mock(:github, omniauth_hash)
Run Code Online (Sandbox Code Playgroud)

然后在任何测试之前需要它:

before do
    request.env['omniauth.auth'] = OmniAuth.config.mock_auth[:github]
end
Run Code Online (Sandbox Code Playgroud)

现在您应该能够使用 Omniauth 创建用户,如下例所示:

describe SessionsController do
    it "should successfully create a user" do
        expect {
            post :create, provider: :github
        }.to change{ User.count }.by(1)
    end
end
Run Code Online (Sandbox Code Playgroud)

所有功劳都归功于来自http://natashatherobot.com的 Natasha在她的博客中发布了这个答案。