3

I am trying to move a helper method from a controller test to the test_helper.rb:

# example_controller_test.rb
require 'test_helper'
class ExampleControllerTest < ActionController::TestCase
  should 'get index' do
    turn_off_authorization
    get :show
    assert_response :success
  end
end

# test_helper.rb
class ActionController::TestCase
  def turn_off_authorization
    ApplicationController.any_instance
                         .expects(:authorize_action!)
                         .returns(true)
  end
end

However, I'm getting an error:

NameError: undefined local variable or method `turn_off_authorization' for #<ExampleControllerTest:0x000000067d6080>

What am I doing wrong?

sakovias
  • 1,356
  • 1
  • 17
  • 26

1 Answers1

2

Turns out that I had to wrap the helper method into a module:

# test_helper.rb
class ActionController::TestCase
  module CheatWithAuth do
    def turn_off_authorization
      # some code goes here
    end
  end

  include CheatWithAuth
end

I still don't know why the original version didn't work.

The idea came from another answer: How do I write a helper for an integration test in Rails?

Edit: Another solution just came from my friend:

# test_helper.rb
class ActiveSupport::TestCase
  def turn_off_authorization
    # some code goes here
  end
end

Note that ActiveSupport::TestCase (not ActionController::TestCase) is being used here.

Community
  • 1
  • 1
sakovias
  • 1,356
  • 1
  • 17
  • 26