Rails 5をminitestで使用しています。 omniauthに依存するセッションコントローラーへのログインをモックしたいです(ログインにはGoogleと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"]」はnilと評価されています。
回答:
回答№1は0ザ OmniAuthドキュメント 状態
OmniAuthをテストしようとすると、2つの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
.