【问题标题】:How do I mock an OmniAuth hash using Rails and minitest?如何使用 Rails 和 minitest 模拟 OmniAuth 哈希?
【发布时间】:2018-02-01 17:53:19
【问题描述】:

我正在使用带有 minitest 的 Rails 5。我想模拟登录到我的会话控制器,它依赖于omniauth(我使用谷歌和FB登录)。我的控制器测试中有这个,test/controllers/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"]' 的评估结果为零。

【问题讨论】:

    标签: ruby-on-rails mocking ruby-on-rails-5 omniauth minitest


    【解决方案1】:

    OmniAuth docs 状态

    当您尝试测试 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 之后。

    【讨论】:

      猜你喜欢
      • 2018-06-20
      • 1970-01-01
      • 2020-02-23
      • 2020-08-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-21
      • 1970-01-01
      相关资源
      最近更新 更多