如何存根Time.now.hour

时间:2015-05-25 17:04:57

标签: ruby-on-rails testing time rspec stubbing

我有一个帮助方法,可以在视图中输出问候语#{greet(Time.now.hour)},等待时间:

users_helper.rb:

def greet(hour_of_clock)
 if hour_of_clock >= 1 && hour_of_clock <= 11
  "Morning"
 elsif hour_of_clock >= 12 && hour_of_clock <= 16
  "Afternoon"
 else
  "Evening"
 end
end

我正试图测试这个失败,如下所示:

users_feature_spec.rb

describe 'greeting a newly registered user' do
  before do 
    @fake_time = Time.parse("11:00")
    Time.stub(:now) { @fake_time }
  end
  it 'tailors the greeting to the time of day' do
    visit '/'
    fill_in 'Name here...', with: 'test name'
    fill_in 'Your email here...', with: 'test@test.com'
    click_button 'Notify me'

    expect(page).to have_content 'Morning'
  end
end

测试失败,因为Time.now.hour没有如上所述存根。

由于各种建议,我现在尝试了各种各样的变化,这两个主要的重新格式至少看起来在语法上是正确的:

describe 'greeting a newly registered user' do
  before do 
    @fake_time =  Time.parse("11:00")
    allow(Time).to receive(:now).and_return(@fake_time)  
  end
  it 'tailors the greeting to the time of day' do
      visit '/'
      fill_in 'Name here...', with: 'test name'
      fill_in 'Your email here...', with: 'test@test.com'
      click_button 'Notify me'

      expect(page).to have_content 'Morning'
    end
  end

并使用新的ActiveSupport :: Testing :: TimeHelpers方法#travel_to:

describe 'greeting a newly registered user' do
  it 'tailors the greeting to the time of day' do
    travel_to Time.new(2013, 11, 24, 01, 04, 44) do
      visit '/'
      fill_in 'Name here...', with: 'test name'
      fill_in 'Your email here...', with: 'test@test.com'
      click_button 'Notify me'

      expect(page).to have_content 'Morning'
    end
  end

但我仍然做错了,这意味着#greet仍在使用Time.now.hour的实时输出而不使用我的存根或travel_to时间值。有什么帮助吗?

3 个答案:

答案 0 :(得分:2)

你可以试试这个:

let!(:fake_hour) { '11' }
before do 
  allow(Time).to receive_message_chain(:now, :hour).and_return(fake_hour)
end

答案 1 :(得分:1)

另一种方法是使用Timecop(或new Rails replacement travel_to)为您留出时间。使用Timecop,您可以拥有超级可读的规格而无需手动存根:

# spec setup

Timecop.freeze(Time.now.beginning_of_day + 11.hours) do
  visit root_path
  do_other_stuff!
end

答案 2 :(得分:0)

我放弃尝试自己或使用::TimeHelpers方法#travel_to :(并使用Timecop gem,第一次如下工作:

before do 
    Timecop.freeze(Time.now.beginning_of_day + 11.hours)
end

it 'tailors the greeting to the time of day' do
    visit '/'
    fill_in 'Name here...', with: 'test name'
    fill_in 'Your email here...', with: 'test@test.com'
    click_button 'Notify me'

    expect(page).to have_content 'Morning'
end

我真的很想了解我原来的方法失败了,有没有人看到出了什么问题?