0

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

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 中配置了 OmniAuth config/environments/test.rb,我很确定该文件在应用程序启动时运行。

4

1 回答 1

1

我看到了几个问题。一方面,您不是在测试登录操作。您正在使用请求中的 oauth 数据执行控制器操作,并期望它通过身份验证。Oauth 数据不像 API 密钥,不会让您像那样自动登录。您必须点击omniauth 提供的特定登录操作,然后设置您的用户会话。这应该自行测试,以确认您的整个 oauth 登录策略按预期工作。如果您正在测试与 oauth 登录行为不直接相关的控制器操作,那么您应该在运行需要身份验证的测试之前使用设计测试帮助程序来登录用户。

此外,您不希望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 
于 2017-01-05T03:05:01.113 回答