0

我已經用omniauth-facebook寶石申請了。我的所有rails測試都通過了,但在添加代碼以檢查經過身份驗證的用戶訪問某些操作後 - 我的一些測試失敗。我怎樣才能將代碼添加到我的測試中以登錄「測試」用戶,以便我可以模擬經過身份驗證的用戶?大多數谷歌搜索結果都顯示了Rspec或Devise示例的示例,但我一直使用Rails 5的默認測試套件,所以我很難找到一些如何正確執行此操作的示例。如果您希望我提供我當前測試的任何特定樣本,請告訴我。想到包括什麼相關的內容,因爲我不知道從哪裏開始。如何使用Omniauth gem登錄用戶進行Rails測試?

+0

你可以只存根正在檢查驗證用戶的方法 – Kkulikovskis

回答

0

所以這裏通讀文件here,並嘗試各種事情之後就是我想出了...

測試/ 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 protected]' }}) 

    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 

的config/routes.rb中

Rails.application.routes.draw do 
    #... 
    get 'auth/facebook/callback', to: 'sessions#create' 
    #... 
    end 
相關問題