How to sign_in for Devise to Test Controller with Minitest

前端 未结 2 1300
慢半拍i
慢半拍i 2021-01-05 16:54

I\'m newbie to Rails Testing.

After following some tutorial online, I could able to setup and run testing for Model.

But when trying to test for Cont

2条回答
  •  鱼传尺愫
    2021-01-05 17:55

    In your test_helper.rb file's ActiveSupport::TestCase class, add a new method log_in_as like this:

    require "test_helper"
    ENV["RAILS_ENV"] = "test"
    require File.expand_path("../../config/environment", __FILE__)
    require "rails/test_help"
    require "minitest/rails"
    require "minitest/reporters"
    Minitest::Reporters.use!(
        Minitest::Reporters::SpecReporter.new,
        ENV,
        Minitest.backtrace_filter
    )
    
    class ActiveSupport::TestCase
      fixtures :all
      include FactoryGirl::Syntax::Methods
    
      # Returns true if a test user is logged in.
      def is_logged_in?
        !session[:user_id].nil?
      end
    
      # Logs in a test user.
      def log_in_as(user, options = {})
        password    = options[:password]    || 'password'
        remember_me = options[:remember_me] || '1'
        if integration_test?
          post login_path, session: { email:       user.email,
                                      password:    password,
                                      remember_me: remember_me }
        else
          session[:user_id] = user.id
        end
      end
    
      private
    
      # Returns true inside an integration test.
      def integration_test?
        defined?(post_via_redirect)
      end
    end
    
    class ActionController::TestCase
      include Devise::TestHelpers
    end
    

    Then, use this log_in_as method instead of sign_in in your test:

    require "test_helper"
    
    class AwardedBidsControllerTest < ActionController::TestCase
      test "should get index" do
        user = create(:user)
        log_in_as user
        get :index
        assert_response :success
      end
    end
    

提交回复
热议问题