Borsunho
Borsunho

Reputation: 1167

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.

Upvotes: 2

Views: 1247

Answers (1)

Alter Lagos
Alter Lagos

Reputation: 12550

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.

Upvotes: 1

Related Questions