stub any_instance using Minitest

André Ricardo picture André Ricardo · Oct 31, 2014 · Viewed 10.4k times · Source

How can I do the following without using any_instance from Mocha? I just want to test a protected Controller as described here without using Rspec.

class PortfoliosControllerTest < ActionController::TestCase

  setup do
    @portfolio = portfolios(:p2)
    user = @portfolio.user

    token = Doorkeeper::AccessToken.create!(application_id: 'minitest',
                                            resource_owner_id: user.id)
    PortfoliosController.any_instance.stubs(:doorkeeper_token).returns(token)
  end
end

Answer

blowmage picture blowmage · Oct 31, 2014

You don't need to stub any instance of PortfoliosController, just the instance that the test is using. This is available in the @controller variable, as explained in the ActionController::TestCase documentation.

class PortfoliosControllerTest < ActionController::TestCase

  setup do
    @portfolio = portfolios(:p2)
    user = @portfolio.user

    token = Doorkeeper::AccessToken.create!(application_id: 'minitest',
                                            resource_owner_id: user.id)
    @controller.stubs(:doorkeeper_token).returns(token)
  end
end