Kamilski81
Kamilski81

Reputation: 15117

How do I access a helper method when I am running a test in rails?

I am writing a test for my email service, inside my email template file I call a helper method called: do_it, which is defined inside application_helper.rb

However, when i run my tests they fail because the helper methods are not imported, I get the following exception:

NoMethodError: undefined method `do_it' 

Any idea / suggestions on how i can import helper methods into tests?

I am using:

require 'test_helper'

class NotifierTest < ActionMailer::TestCase

Upvotes: 1

Views: 201

Answers (1)

brentvatne
brentvatne

Reputation: 8038

A Helper is just a module containing instance level methods. RSpec gives you a way to access this by default in the Helper specs that are automatically generated, by using helper.x within the describe block for the helper. If you're not using RSpec, there may be some other method provided by your test framework. Alternatively, you can mix the module into a class and test on an instance of the class.

Somewhere in the test setup:

class ApplicationHelperTest; include ApplicationHelper; end
@helper = ApplicationHelperTest.new

And in your test:

assert @helper.do_it

To better address your exact issue, what you need to do then is include the helper in the class that the method is being called on. For example, let's say the class is Mailer:

Mailer.send(:include, ApplicationHelper)

Upvotes: 1

Related Questions