title: How to stub Time.now.hour
body: <p>I have a helper method which outputs a greeting <code>#{greet(Time.now.hour)}</code> in the view pending the time of day:</p>
  
  <p>users_helper.rb:</p>
  
  <pre><code>def greet(hour_of_clock)
   if hour_of_clock &gt;= 1 &amp;&amp; hour_of_clock &lt;= 11
    "Morning"
   elsif hour_of_clock &gt;= 12 &amp;&amp; hour_of_clock &lt;= 16
    "Afternoon"
   else
    "Evening"
   end
  end
  </code></pre>
  
  <p>And I am trying to test this unsuccessfully as below:</p>
  
  <p>users_feature_spec.rb</p>
  
  <pre><code>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
  </code></pre>
  
  <p>The test fails as the Time.now.hour is not being stubbed as intended above.</p>
  
  <p>I've now tried all sorts of variations thanks to various advice, the two main reformats which it at least seemed were syntactically correct were:</p>
  
  <pre><code>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
  </code></pre>
  
  <p>and using the new ActiveSupport::Testing::TimeHelpers method #travel_to:</p>
  
  <pre><code>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
  </code></pre>
  
  <p>But still I'm doing something wrong which means that <code>#greet</code> is still taking the live output of <code>Time.now.hour</code> and not using my stubbed or travel_to Time value. Any help please?</p>