0

I'm writing tests for a Rail 5 app and I'm struggling to test signed-in functionality. I'm using Minitest and Omniauth (specifically Google OAuth).

Most of my methods check for current_user and redirect to root_path if it's not present. I need to write tests that simulate that current_user, preferably specifying the id.

If I do something like this:

test "should load settings for logged in user" do
  current_user = {id:1}
  get settings_path
  assert_response :success
end

The test fails with a redirect to my root_path. I've tried to dig into this and it looks like current_user isn't set when the controller checks.

Apologies if I'm missing something fundamental, but could someone please explain how I can test logged-in functionality?

Imran Ali
  • 2,223
  • 2
  • 28
  • 41
Steve
  • 1
  • `current_user = {id:1}` just sets a local variable in the block. How exactly to do this depends on how the authentication system is implemented. You could stub the `current_user` method or do a post request to your login method. Devise/Warden have built in testing methods. – max Oct 10 '17 at 00:35
  • The `current_user` method is part of ApplicationController, I'm not having much luck attempting to stub that. – Steve Oct 10 '17 at 09:33
  • you cannot access current_user in test cases. You can sign in with user having id 1. Like this sign_in User.find(1). if you already have users data in test enviornment – Zia Qamar Oct 11 '17 at 12:43
  • https://github.com/omniauth/omniauth/wiki/Integration-Testing – Zia Qamar Oct 11 '17 at 12:46
  • Thanks folks. I struggled to follow the integration test instructions on their GitHub wiki but figured out I need to do: 1. `get "/auth/google_oauth2"` 2. `OmniAuth.config.mock_auth[:google_oauth2] = OmniAuth::AuthHash.new({ ... })` 3. `get "/auth/google_oauth2/callback"` – Steve Oct 14 '17 at 14:03

0 Answers0