How to call 'time_ago_in_words' from a FunctionalTest?
Asked Answered
L

4

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?

Lynea answered 11/2, 2010 at 16:9 Comment(0)
P
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"
Prytaneum answered 11/2, 2010 at 16:47 Comment(3)
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!Readjust
From the console, you can also access helper functions with irb(main):110:0> helper.time_ago_in_words 3.minutes.agoKlehm
@jpemberthy, including this within a model in production can cause performance issues?Douma
B
1

I added on rails_helper.rb

config.include ActionView::Helpers::DateHelper

and work's, thank's @jpemberthy!

Benzol answered 25/1, 2018 at 23:21 Comment(0)
G
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.

Guendolen answered 13/2, 2015 at 18:34 Comment(0)
S
-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.

Subject answered 11/2, 2010 at 16:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.