如何使用RSpec 3.5测试此代码?

时间:2017-01-20 19:59:59

标签: ruby-on-rails ruby rspec

我需要测试这段代码。它在我的rails应用程序中的application_helper内部。

def greet
  now = Time.now
  today = Date.today.to_time

  morning = today.beginning_of_day
  noon = today.noon
  evening = today.change( hour: 17 )
  night = today.change( hour: 20 )
  tomorrow = today.tomorrow

  if (morning..noon).cover? now
    'Good Morning'
  elsif (noon..evening).cover? now
    'Good Afternoon'
  elsif (evening..night).cover? now
    'Good Evening'
  end
end

1 个答案:

答案 0 :(得分:1)

我建议使用Timecop gem来测试基于时间的代码。有关测试帮助程序的文档,请参阅RSpec documentation

你可以这样写:

RSpec.describe ApplicationHelper, type: :helper do
  describe '#greet' do
    subject { helper.greet }

    context 'in the morning' do
      around do |example|
        Timecop.travel(Time.now.change(hour: 2), &example)
      end

      it { is_expected.to eq('Good Morning') }
    end
  end
end

这里发生的事情是around块会调用timecop到"回到过去" (即模拟特定时间),运行示例并在之后返回到常规行为。使用Timecop时,您需要确保不要忘记返回原始时间,因此建议使用around块。