我在视图中使用'time_ago_in_words' 函数,我需要在FunctionalTest 中测试输出。
但是测试看不到'time_ago_in_words'辅助函数。
为了使用 FunctionalTests 中的这些辅助方法,我应该怎么做?
我在视图中使用'time_ago_in_words' 函数,我需要在FunctionalTest 中测试输出。
但是测试看不到'time_ago_in_words'辅助函数。
为了使用 FunctionalTests 中的这些辅助方法,我应该怎么做?
ActionView::Helpers::DateHelper
将模块包含在您的test_helper.rb
或test.rb
文件中。就是这样,从测试控制台:
>> 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"
我加了rails_helper.rb
config.include ActionView::Helpers::DateHelper
和工作,谢谢@jpemberthy!
我最近遇到了一个类似的问题,我试图从 API 访问这个函数,所以我将它包装在一个名为 timeywimey 的 gem 中。看看:https ://github.com/onetwopunch/timeywimey#usage
它允许您从 Rails 项目以及 Sinatra 和本机 ruby 项目中的任何位置访问此帮助程序。
你到底想测试什么?您不需要验证time_ago_in_words
自身的行为,因为 Rails 自己的测试已经涵盖了这一点。如果您正在测试自己的一个使用 的助手,time_ago_in_words
则可以在助手测试(继承自ActionView::TestCase
)中检查输出。
功能测试旨在验证控制器的行为(它们呈现什么模板,它们是否允许访问、重定向等),其中可以包括检查某些 HTML 标记的存在(通过 id)。我通常尽量避免使用它们来检查标签的内容。