0

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.

Neil Slater
  • 26,512
  • 6
  • 76
  • 94
jriff
  • 1,947
  • 3
  • 23
  • 33

2 Answers2

0

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
Neil Slater
  • 26,512
  • 6
  • 76
  • 94
  • And how about the Konfig class? What would you do there? – jriff Jul 31 '13 at 07:53
  • I have suggested in my snippet to use `mocha` to stub it with a value for the test. The syntax for it is from memory, mind, it may need tweaking. Try and avoid asserting exactly how many times it is called - it is enough to just know that the config value is used to control the behaviour of the method. – Neil Slater Jul 31 '13 at 08:27
0

Use mock framework like rspec-mock, rr mock

allenwei
  • 4,047
  • 5
  • 23
  • 26