How to make helper methods available in a Rails integration test?

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

In the other posts I read, it's possible by including require sessions_helper in the test file, but I still get the error message 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 
+5
source share
2 answers

Your messagae error says:

 NameError: undefined local variable or method 'my_preference' 

which means that you do not have access to the my_preference method. To make this available in your class, you must include use the module in your class.

You must include your module: SessionsHelper in your PreferencesTest class.

 include SessionsHelper 

Then the instance method my_preference will be available for 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 
+7
source

If someone wants to have special helper methods available in all tests, helper modules can be included in the test_helper.rb file:

 class ActiveSupport::TestCase ... include SessionsHelper end 
+1
source

All Articles