如何使用 Rails 和 minitest 模拟 OmniAuth 哈希



我正在使用带有minitest的Rails 5。 我想模拟登录到我的会话控制器,它依赖于全身份验证(我使用 Google 和 FB 进行登录(。 我在我的控制器测试中都有这个,测试/控制器/rates_controller_test.rb,

 class RatesControllerTest < ActionDispatch::IntegrationTest
  # Login the user
  def setup
    logged_in_user = users(:one)
    login_with_user(logged_in_user)
  end

然后我尝试在我的测试助手test/test_helper.rb中设置登录,

class ActiveSupport::TestCase
  # Setup all fixtures in test/fixtures/*.yml for all tests in alphabetical order.
  fixtures :all
  def setup_omniauth_mock(user)
    OmniAuth.config.test_mode = true
    omniauth_hash = { 'provider' => 'google',
                      'uid' => '12345',
                      'info' => {
                         'name' => "#{user.first_name} #{user.last_name}",
                          'email' => user.email,
                      },
                      'extra' => {'raw_info' =>
                                      { 'location' => 'San Francisco',
                                        'gravatar_id' => '123456789'
                                      }
                      }
    }
    OmniAuth.config.add_mock(:google, omniauth_hash)
  end
  # Add more helper methods to be used by all tests here...
  def login_with_user(user)
    setup_omniauth_mock(user)
    post sessions_path
  end
但是,当我运行控制器测试时,

当我在会话控制器中评估此行时,我得到一个 nil 值......

user = User.from_omniauth(env["omniauth.auth"])

上面,'env["omniauth.auth"]'的评估结果为零。

OmniAuth 文档状态

当您尝试测试OmniAuth时,您需要设置两个env变量

并提供使用 RSpec 的示例

before do
  Rails.application.env_config["devise.mapping"] = Devise.mappings[:user] # If using Devise
  Rails.application.env_config["omniauth.auth"] = OmniAuth.config.mock_auth[:twitter]
end

在您的情况下,似乎您可能需要设置

Rails.application.env_config["omniauth.auth"] = OmniAuth.config.mock_auth[:google]

在您的setup_omniauth_mock方法中,调用 OmniAuth.config.add_mock .

最新更新