如何使用Rails和minitest模拟OmniAuth哈希? [英] How do I mock an OmniAuth hash using Rails and minitest?
问题描述
我正在使用带有minitest的Rails 5.我想模拟登录到会话控制器的会话,该控制器依赖于omniauth(我使用Google和FB进行登录).我的控制器测试中有这个,test/controllers/rates_controller_test.rb,
I'm using Rails 5 with minitest. I want to mock logging into my sessions controller, which relies on omniauth (I use Google and FB for login). I have this in my controller 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
and then I try and set up login in my test helper, 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值...
However, when I run my controller test, I'm getting a nil value when this line is evaluated in my sessions controller ...
user = User.from_omniauth(env["omniauth.auth"])
上面,'env ["omniauth.auth"]'计算为nil.
Above, 'env["omniauth.auth"]' is evaluating to nil.
推荐答案
当您尝试测试OmniAuth时,您需要设置两个环境变量
When you try to test the OmniAuth, you need to set two env variables
并提供使用RSpec的示例
and provide examples using 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
根据您的情况,似乎您可能需要设置
In your case, it seems like you may need to set
Rails.application.env_config["omniauth.auth"] = OmniAuth.config.mock_auth[:google]
调用OmniAuth.config.add_mock
之后,在setup_omniauth_mock
方法中
.
in your setup_omniauth_mock
method, after the call to OmniAuth.config.add_mock
.
这篇关于如何使用Rails和minitest模拟OmniAuth哈希?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!