6

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
André Ricardo
  • 3,051
  • 7
  • 23
  • 32
  • 1
    Have you seen this solution for stubbing with no libraries? http://stackoverflow.com/a/10329105/356060 – TuteC Nov 10 '14 at 00:44

3 Answers3

7

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
blowmage
  • 8,854
  • 2
  • 35
  • 40
4

I'd recommend checking out this gem. Would allow you to do something like...

class PortfoliosControllerTest < ActionController::TestCase
  def cool_test
    PortfoliosController.stub_any_instance(:doorkeeper_token, token) do
      # Assert whatever you were going to assert
    end
  end
end

kind of nice not to have to worry about setup either.

jamesconant
  • 1,405
  • 1
  • 12
  • 18
1

'no Mocha' version of 'blowmage' answer

 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.stub(:doorkeeper_token,token) do
      #do your tests
    end
  end
end

see http://www.rubydoc.info/gems/minitest/4.2.0/Object:stub

Foton
  • 1,197
  • 13
  • 24