ruby on rails -如何存根时间.现在.小时



我有一个助手方法,它在等待一天的时间的视图中输出问候语#{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

和使用新的activessupport::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时间值。请帮忙好吗?

你可以试试:

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

另一种方法是使用Timecop(或新的Rails替代品travel_to)为您记录时间。使用Timecop,您可以拥有超级可读的规范,而无需手动存根:

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

我放弃了尝试自己存根或使用::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

我真的很想了解我原来的方法失败的地方,有人看到哪里出错了吗?

相关内容

  • 没有找到相关文章

最新更新