![](/img/trans.png)
[英]How do I NOT require user's email when using Rails Omniauth gem and Google OpenID
[英]How can I login a user for my Rails tests using Omniauth gem?
我已經使用omniauth-facebook gem制作了一個應用程序。 我所有的Rails測試都通過了,但是在添加代碼以檢查經過身份驗證的用戶是否可以訪問某些操作之后,我的某些測試失敗了。 如何將代碼添加到測試中以登錄“測試”用戶,以便模擬經過身份驗證的用戶? Google的大多數結果都顯示了Rspec或Devise示例的示例,但是我一直在使用Rails 5的默認測試套件,因此,我很難找到一些有關如何正確執行此操作的示例。 如果您希望我提供當前測試的任何特定樣本,請告訴我。 由於我不確定從哪里開始,因此沒有任何相關的內容要考慮在內。
因此,在閱讀完此處的文檔並嘗試了各種操作之后,這就是我想出的...
測試/ test_helper.rb中
ENV['RAILS_ENV'] ||= 'test'
require File.expand_path('../../config/environment', __FILE__)
require 'rails/test_help'
class ActiveSupport::TestCase
# Setup all fixtures in test/fixtures/*.yml for all tests in alphabetical order.
fixtures :all
OmniAuth.config.test_mode = true
OmniAuth.config.add_mock(:facebook, {:uid => '123456', info: { email: 'email_address_of_user_in_fixtures@gmail.com' }})
def sign_in_admin
Rails.application.env_config["omniauth.auth"] = OmniAuth.config.mock_auth[:facebook]
get auth_facebook_callback_path
end
end
測試/控制器/ restaurants_controller_test.rb
require 'test_helper'
class RestaurantsControllerTest < ActionDispatch::IntegrationTest
setup do
# I sign in an admin user, and proceed
sign_in_admin
@restaurant = restaurants(:mcdonalds)
end
# other test methods for actions ...
end
配置/ routes.rb中
Rails.application.routes.draw do
#...
get 'auth/facebook/callback', to: 'sessions#create'
#...
end
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.