nil:NilClass、RSpec、OmniAuth 的未定义方法“提供者”

undefined method `provider' for nil:NilClass, RSpec, OmniAuth

我正在尝试使用 RSpec 和 OmniAuth 测试经过身份验证的控制器。我遵循了他们 wiki 上的 integration testing 指南。当我 运行 测试时,出现以下错误:

Failure/Error:
       where(provider: auth.provider, uid: auth.uid).first_or_initialize.tap do |user|
        user.provider = auth.provider
        user.uid = auth.uid
        user.first_name = auth.info.first_name
        user.last_name = auth.info.last_name
        user.email = auth.info.email
        user.picture = auth.info.image
        user.save!
       end

     NoMethodError:
       undefined method `provider' for nil:NilClass

在此gist中提供了所有相关代码。我的直觉是模拟身份验证哈希没有以某种方式设置,但我无法验证这一点。我在 config/environments/test.rb 中配置了 OmniAuth,如 Gist 所示,我很确定当应用程序启动时该文件是 运行。

我发现了几个问题。首先,您没有测试登录操作。您正在使用请求中的 oauth 数据执行控制器操作并期望它通过身份验证。 Oauth 数据不像 API 密钥,不会让您那样自动登录。您必须点击 omniauth 提供的特定登录操作,然后设置您的用户会话。这应该单独测试以确认您的整个 oauth 登录策略按预期工作。如果您正在测试与 oauth 登录行为不直接相关的控制器操作,那么您应该在 运行 需要身份验证的测试之前使用 the devise test helpers 登录用户。

此外,您不希望在环境初始化程序中设置 OmniAuth 配置。文档建议,我自己做的是在测试中设置配置。一方面,这允许您测试不同类型的场景。例如,这就是我测试我的 omniauth 回调控制器是否正常工作并执行我想要的操作的方式:

context 'with valid google credentials' do
  # this should actually be created in a factory
  let(:provider) { :google_oauth2 }
  let(:oauth) { OmniAuth::AuthHash.new provider: provider, uid: '1234' }
  before do
    OmniAuth.config.test_mode = true
    OmniAuth.config.mock_auth[provider] = oauth
  end

  it 'creates a new user' do
    expect { visit "/users/auth/#{provider}" }.to change(User, :count).by(1)
  end
end