ruby-on-railsrubyruby-on-rails-5minitestsorcery

How to stub current_user in Rails 5?


How do I stub current_user in Rails 5?

I expected this:

@controller.stub :current_user, mock_user do

end

to work, but there is no @controller in ActionDispatch::IntegrationTest? I use sorcery gem for authentication.


Solution

  • You could try the wiki example:

    class TeamsControllerTest < ActionController::TestCase
      include Sorcery::TestHelpers::Rails::Integration
      include Sorcery::TestHelpers::Rails::Controller
    
      setup do
        @team = teams(:one)
        @user = users(:one)
    
        login_user(user = @user, route = login_url)  # replace with your login url path
      end
    
      test "should get index" do
        get :index
        assert_response :success
        assert_not_nil assigns(:teams)
      end
    

    That will set your test user as current_user.