Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 749
Marty Avatar asked Aug 15 '15 21:08

Marty


People also ask

Can we use helper method in controller Rails?

In Rails 5, by using the new instance level helpers method in the controller, we can access helper methods in controllers.

Why helper is used in Rails?

Basically helpers in Rails are used to extract complex logic out of the view so that you can organize your code better.

What is Minitest in Ruby on Rails?

What is Minitest? Minitest is a testing suite for Ruby. It provides a complete suite of testing facilities supporting test-driven development (TDD), behavior-driven development (BDD), mocking, and benchmarking. It's small, fast, and it aims to make tests clean and readable.


1 Answers

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
like image 185
K M Rakibul Islam Avatar answered Oct 13 '22 14:10

K M Rakibul Islam