如何给rspec假Time.now值

时间:2014-03-08 10:42:03

标签: ruby rspec

我正在尝试编写一个rspec测试。这是我的代码。

# mylogger.rb
class MyLogger
  def save
    File.open("#{Time.now.strftime('%Y%m%d%H')}.log","w"){|f| f.puts "log" }
  end
end

# mylogger_spec.rb
require 'mylogger'

describe MyLogger, "#save" do
  it "saves a log file" do
    logger = MyLogger.new
    logger.save
    # check whether proper file has been written.
  end
end

如何设置假Time.now值,并为此方法编写测试?

2 个答案:

答案 0 :(得分:2)

使用像Timecop这样的宝石(参见:https://github.com/travisjeffery/timecop

答案 1 :(得分:0)

我会提取文件名创建并单独测试它。类似的东西:

# mylogger.rb
class MyLogger
  def save
    File.open(filename, "w") { |f| f.puts "log" }
  end

  def filename(time = Time.now)
    "#{time.strftime('%Y%m%d%H')}.log"
  end
end

# mylogger_spec.rb
require 'mylogger'

describe MyLogger do
  describe "#save" do
    it "saves a log file" do
      logger = MyLogger.new
      logger.stub(:filename) { "test.log" }
      logger.save
      # check whether "test.log" has been written.
    end
  end

  describe "#filename" do
    it "creates a nice filename" do
      logger = MyLogger.new
      time = Time.new(2002, 10, 31, 2)
      logger.filename(time).should == "2002103102.log"
    end
  end
end