Ruby 如何在rspec 3中存根Date.today.strftime?

Ruby 如何在rspec 3中存根Date.today.strftime?,ruby,rspec,rspec3,Ruby,Rspec,Rspec3,我有以下代码: def when_to_change year, month = Date.today.strftime("%Y %m").split(' ').map {|v| v.to_i} if month < 9 year + 2 else year + 3 end end 当我尝试运行规范时,它看起来不是这样的。我做错了什么 我使用rspecv3.3.2 回答 由于Date.today在每次方法调用时都返回新对象

我有以下代码:

  def when_to_change
    year, month = Date.today.strftime("%Y %m").split(' ').map {|v| v.to_i}
    if month < 9
      year + 2
    else 
      year + 3
    end
  end
当我尝试运行规范时,它看起来不是这样的。我做错了什么

我使用rspec
v3.3.2

回答

由于
Date.today
在每次方法调用时都返回新对象,可以通过以下方式完成:

  it 'when current month at the of a year' do
    allow(Date.today).to receive(:strftime).with('%Y %m').and_return('2015 10')
    expect(@car.when_to_change).to eq(2018)
  end

  it 'when current month earlier than september' do 
    allow(Date.today).to receive(:strftime).with('%Y %m').and_return('2015 07')
    expect(@car.when_to_change).to eq(2017)
  end
  it 'when current month earlier than september' do 
     allow(Date).to receive(:today).and_return(Date.new(2015, 7, 19))
     expect(@car.when_to_change).to eq(2017)
  end

感谢@DmitrySokurenko的解释

日期。今天总是返回新对象。首先,今天将
存根

我的意思是:

>> Date.today.object_id
=> 70175652485620
>> Date.today.object_id
=> 70175652610440
所以当你下次调用
时,那是一个不同的对象


因此,要么存根
Date.today
以返回某个固定日期,要么将代码更改为使用类似于
SomeHelper.today
的内容,它将在测试环境中始终返回相同的日期。

日期。today
始终返回新对象。首先,今天将
存根

我的意思是:

>> Date.today.object_id
=> 70175652485620
>> Date.today.object_id
=> 70175652610440
所以当你下次调用
时,那是一个不同的对象


因此,要么存根
日期。今天
要返回某个固定日期,要么将代码更改为使用类似于
SomeHelper的内容。今天
在测试环境中总是返回相同的日期。

我认为这正是您需要的。

我认为这正是您需要的。

您不需要Timecop来做这件事。Rails已经内置了类似的东西:

然后:

travel_to(Date.parse('2015-10-01')) do
  expect(@car.when_to_change).to eq(2018)
end

你不需要时间警察来做那件事。Rails已经内置了类似的东西:

然后:

travel_to(Date.parse('2015-10-01')) do
  expect(@car.when_to_change).to eq(2018)
end

我明白你说的话,但我还没有想出任何可行的办法。目前,我尝试了
allow(Date.)。接收(:today.)和返回(2015,7,19)
,但这不起作用。你能帮我吗?创建一些日期:
the_today=date.new(date.new(2015,11,19));允许(日期)。接收(:今天)。然后返回(今天)
,然后在上面存根你需要的所有内容。为什么我需要nest
Date.new
就像你做的那样
Date.new(Date.new(2015,11,19))
?哦,对不起,这是一个打字错误,应该只有一个
Date.new
我理解你说的话,但我还没有想出任何可行的方法来做这件事。目前,我尝试了
allow(Date.)。接收(:today.)和返回(2015,7,19)
,但这不起作用。你能帮我吗?创建一些日期:
the_today=date.new(date.new(2015,11,19));允许(日期)。接收(:今天)。然后返回(今天)
,然后在上面存根您需要的所有内容。为什么我需要nest
Date.new
像您一样
Date.new(Date.new(2015,11,19))
?哦,对不起,这是一个打字错误,应该只有一个
Date.new