Marty Marty - 5 months ago 8
Ruby Question

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

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

Answer

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