“Travel”时间辅助工具在功能规格中不可用吗?

31

我刚试图在我的一个功能规范中使用Rails的时间辅助方法travel

scenario 'published_at allows to set a publishing date in the future' do
  magazine_article.update_attribute(:published_at, Time.now + 1.day)
  expect { visit magazine_article_path(magazine_article.magazine_category, magazine_article) }
         .to raise_error(ActiveRecord::RecordNotFound)

  travel 2.days do
    visit magazine_article_path(magazine_article.magazine_category, magazine_article)
    expect(page).to have_content('Super awesome article')
  end
end 
它给我的是这个:
NoMethodError:
   undefined method `travel' for #<RSpec::ExampleGroups::MagazineArticles::AsUser::Viewing:0x007f84a7a95640>
我漏掉了什么?

http://api.rubyonrails.org/classes/ActiveSupport/Testing/TimeHelpers.html

2个回答

55
为了使用这些辅助工具,您必须将它们包含到您的测试中。 您可以通过将其包含在单个测试套件中来实现:
describe MyClass do
  include ActiveSupport::Testing::TimeHelpers
end

或者全球范围内:

RSpec.configure do |config|
  config.include ActiveSupport::Testing::TimeHelpers
end

11
请勿忘记要求文件require 'active_support/testing/time_helpers' - MegaTux
有人知道不想将其全局包含的典型原因吗? - kluka
1
@kluka,只使用实际需要的代码是一个好习惯。你所需的代码越多,程序运行速度就会越慢。我通常根本不需要时间助手,或者只在特定的地方稍后才需要。 - Robin

4

接着 @andrey-deineko 的发言...

我在 spec\support 目录下创建了一个名为 time_helpers.rb 的文件,内容如下:

RSpec.configure do |config|
  config.include ActiveSupport::Testing::TimeHelpers
end

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接