lundi 25 mai 2015

How to stub Time.now.hour

I have a helper method which outputs a greeting #{greet(Time.now.hour)} in the view pending the time of day:

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

And I am trying to test this unsuccessfully as below:

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

The test fails as the Time.now.hour is not being stubbed as intended above, can anyone help me understand what I'm doing wrong please? Thanks.

Aucun commentaire:

Enregistrer un commentaire