7

I have a helper file in app/helpers/sessions_helper.rb that includes a method my_preference which returns the preference of the currently logged in user. I would like to have access to that method in an integration test. For example, so that I can use get user_path(my_preference) in my tests.

In other posts I read this is possible by including require sessions_helper in the test file, but I still get the error NameError: undefined local variable or method 'my_preference'. What am I doing wrong?

require 'test_helper'
require 'sessions_helper'

class PreferencesTest < ActionDispatch::IntegrationTest

  test "my test" do
    ...
    get user_path(my_preference)
  end

end
Marty
  • 2,132
  • 4
  • 21
  • 47

2 Answers2

9

Your error messagae says:

NameError: undefined local variable or method 'my_preference'

which means you don't have access to my_preference method. To make that available in your class, you have to include the module in your class.

You have to include your module: SessionsHelper in your PreferencesTest class.

include SessionsHelper

Then, the instance method my_preference will be available for you to use in your test.

So, you want to do:

require 'test_helper'
require 'sessions_helper'


class PreferencesTest < ActionDispatch::IntegrationTest

  include SessionsHelper

  test "my test" do
    ...
    get user_path(my_preference)
  end

end
K M Rakibul Islam
  • 33,760
  • 12
  • 89
  • 110
  • Thanks, that works! It now also seems to work if I leave out `require 'sessions_helper'`. Does that make sense? Is `require 'sessions_helper'` necessary? – Marty Aug 15 '15 at 22:00
  • yeah, you should not need that if its under `app/helpers` directory let me know! – K M Rakibul Islam Aug 15 '15 at 22:01
3

In case someone wants to have particular helper methods available in all tests, it is possible to include helper modules in the test_helper.rb file:

class ActiveSupport::TestCase 
 ...
 include SessionsHelper
end