Frage

I have this method:

def self.should_restart?
  if Konfig.get(:auto_restart_time).present?
    Time.now>=Time.parse(Konfig.get(:auto_restart_time)) && Utils.uptime_in_minutes>780
  end
end

In regular Ruby (not Rails) how would I go about testing this? I could monkeypatch Konfig and Utils to return what I want but that seems soooo ugly.

War es hilfreich?

Lösung

You may be able to use timecop as part of the solution (which also scores highly for me as "best-named gem, ever"). It is simple to use, and patches most sources of time data in sync, so that if for example your Utils module uses standard methods to assess time, it should have the same concept of "now" as Time.now shows.

Note this won't work if Utils is making a call to external API on another process, in which case you should stub it to return uptime values needed in your test assertions.

The following rspec snippet by way of example, and making some assumptions about what you have available (such as module under test being called Server)

describe "#should_restart?"
  before :each do
    Timecop.travel( Time.parse("2013-08-01T12:00:00") )
    Server.start # Just a guess
    # Using `mocha` gem here
    Konfig.expect(:get).with(:auto_restart_time).returns( "18:00:00" )
  end

  after :each do
    Timecop.return
  end

  it "should be false if the server has just been started" do
    Server.should_restart?.should be_false
  end

  it "should be false before cutoff time" do
    Timecop.travel( Time.parse("2013-08-02T16:00:00") )
    Server.should_restart?.should be_false
  end

  it "should be true when the server has been up for a while, after cutoff time" do
    Timecop.travel( Time.parse("2013-08-02T18:05:00") )
    Server.should_restart?.should be_true
  end
end

Andere Tipps

Use mock framework like rspec-mock, rr mock

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top