How do I mock an OmniAuth hash using Rails and minitest?

僤鯓⒐⒋嵵緔 提交于 2019-12-01 05:40:50

问题


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.


回答1:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!