如何在 Rails 5 中存根 current_user?

How to stub current_user in Rails 5?

如何在 Rails 5 中添加 current_user

我预计会这样:

@controller.stub :current_user, mock_user do

end

可以工作,但是ActionDispatch::IntegrationTest里面没有@controller?我使用 sorcery gem 进行身份验证。

你可以试试 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

这会将您的测试用户设置为 current_user