Skip to content

Instantly share code, notes, and snippets.

@jwo
Created November 5, 2013 17:57
Show Gist options
  • Star 14 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save jwo/7323240 to your computer and use it in GitHub Desktop.
Save jwo/7323240 to your computer and use it in GitHub Desktop.
Devise testing controllers - minitest / rails4
class SecretController < ApplicationController
before_filter :authenticate_user!
def show
end
end
require 'test_helper'
class SecretControllerTest < ActionController::TestCase
include Devise::TestHelpers
test "logged in should get show" do
sign_in users(:one)
get :show
assert_response :success
end
test "not authenticated should get redirect" do
get :show
assert_response :redirect
end
end
@theterminalguy
Copy link

Thanks for sharing, this helped me a lot. But I think it is better to set the sign_in in the setup function and include devise helpers in the test_helper.rb so you would have

class SecretControllerTest < ActionController::TestCase 
   setup do
     sing_in users(:one) 
   end

   test "logged in should get show" do 
      get :show 
      assert_response :success
   end 

   test "not authenticated should get redirect" do
     get :show
     assert_response :redirect
  end
end

Then in your test_helper.rb you can have

class ActiveSupport::TestCase
  fixtures :all
end

class ActionController::TestCase
  include Devise::TestHelpers
end

This way you can use the sign_in function in all your controllers

@seemantasaha
Copy link

I did the same but I am getting the following error:
NoMethodError: undefined method `env' for nil:NilClass

@abla00
Copy link

abla00 commented Oct 27, 2016

Hi, @seemantasaha, please check this out.

  • include Devise::Test::ControllerHelpers on its parent ActionController::TestCase superclass.
  • include Devise::Test::IntegrationHelpers on its parent ActionDispatch::IntegrationTest superclass.

Maybe the root cause is that ControllerTest inherits from IntegrationTest:

class SecretControllerTest < ActionDispatch::IntegrationTest
  include Devise::Test::ControllerHelpers

So make sure what class you inherit from, FYI.

@tannakartikey
Copy link

I did the same but a user is not signing in.
For logged in user also I am getting 302:
Expected response to be a , but was <302>

Found the error. I was not signing in as admin.
Can you describe here for the reference how it works with signing in as admin

Copy link

ghost commented Aug 7, 2017

Thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment