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
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
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"])
Above, 'env["omniauth.auth"]' is evaluating to nil.
The OmniAuth docs state
When you try to test the OmniAuth, you need to set two env variables
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]
in your setup_omniauth_mock
method, after the call to OmniAuth.config.add_mock
.
来源:https://stackoverflow.com/questions/48568917/how-do-i-mock-an-omniauth-hash-using-rails-and-minitest