gpt4 book ai didi

ruby-on-rails - 如何 stub Time.now.hour

转载 作者:行者123 更新时间:2023-11-28 20:06:00 24 4
gpt4 key购买 nike

我有一个辅助方法,它在等待时间的 View 中输出问候语 #{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 没有像上面预期的那样被 stub 。

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

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 的实时输出,而不是使用我的 stubbed 或 travel_to Time值(value)。有什么帮助吗?

最佳答案

你可以试试这个:

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

关于ruby-on-rails - 如何 stub Time.now.hour,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30442942/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com