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

我正在使用Rails 5和minitest。 我想模拟登录我的会话控制器,它依赖于omniauth(我使用谷歌和FB登录)。 我在我的控制器test,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 

但是,当我运行我的控制器测试时,在我的会话控制器中评估此行时,我得到一个零值…

 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] 

在调用OmniAuth.config.add_mock之后的setup_omniauth_mock方法中。