17

I'm using 'time_ago_in_words' function in a view, and I need to test the output in the FunctionalTest.

But the test can not see 'time_ago_in_words' helper function.

What should I do in order to use these helper methods from FunctionalTests?

Raiden
  • 173
  • 1
  • 6

4 Answers4

41

Include the ActionView::Helpers::DateHelper module in your test_helper.rb or test.rb files. And that's it, from the test console:

>> time_ago_in_words(3.minutes.from_now)
NoMethodError: undefined method `time_ago_in_words' for #<Object:0x3b0724>
from (irb):4
from /Users/blinq/.rvm/rubies/ruby-1.9.1-p376/bin/irb:15:in `<main>'
>> include ActionView::Helpers::DateHelper
=> Object
>> time_ago_in_words(3.minutes.from_now)
=> "3 minutes"
jpemberthy
  • 7,473
  • 8
  • 44
  • 52
  • 1
    Argh, that really threw me for a loop, sheesh, I had this code in an initializer file and it couldn't find the method. Thanks! – Bob Sep 15 '11 at 19:21
  • From the console, you can also access helper functions with `irb(main):110:0> helper.time_ago_in_words 3.minutes.ago` – Chloe Jun 03 '15 at 03:28
  • @jpemberthy, including this within a model in production can cause performance issues? – damuz91 Jun 28 '15 at 00:14
1

I added on rails_helper.rb

config.include ActionView::Helpers::DateHelper

and work's, thank's @jpemberthy!

rld
  • 2,603
  • 2
  • 25
  • 39
0

I had a similar issue recently where I was trying to access this function from an API so I wrapped it in a gem called timeywimey. Check it out: https://github.com/onetwopunch/timeywimey#usage

It allows you to access this helper from anywhere in a Rails project as well as Sinatra, and a native ruby project.

onetwopunch
  • 3,279
  • 2
  • 29
  • 44
-1

What exactly are you trying to test? You shouldn't need to verify the behavior of time_ago_in_words itself, because that's covered by Rails' own tests. If you're testing one of your own helpers that uses time_ago_in_words, the output can be checked in a helper test (which inherits from ActionView::TestCase).

Functional tests are intended for verifying the behavior of controllers (what template they render, whether they allow access, redirect, etc) which can include checking for the presence of certain HTML tags (by id). I usually try to avoid using them to check the content of the tags.

Alex Reisner
  • 29,124
  • 6
  • 56
  • 53