5

I have a method like this

class SomeClass
  def self.test_method
    while(true)
      make_heavy_lifting
      sleep(60*60)
    end
  end
end

How do i write test for this method.

one solution i thought of is stubbing sleep method and it worked but i am not able to stub the while keyword. please suggest best practices for unit testing a method which has infinite loop.

nowk
  • 32,822
  • 2
  • 35
  • 40
Sharath B. Patel
  • 401
  • 1
  • 6
  • 15

2 Answers2

6

Maybe you can move everything inside the while except the sleep to another method, then you write specs only for that method, I don't think you really need to test that your method has a while loop and a sleep (you don't need to test EVERY line of your code :P) but if you want to do that check this question, it has some things you can try What is the best practice when it comes to testing "infinite loops"?

Community
  • 1
  • 1
arieljuod
  • 15,460
  • 2
  • 25
  • 36
5

To test this I stub :loop and use that instead of while(true):

class:

class SomeClass
  def self.test_method
    loop do
      make_heavy_lifting
      sleep(60*60)
    end
  end
end

spec:

describe SomeClass do
  describe '#test_method' do
    expect(SomeClass).to receive(:loop).and_yield
    expect(SomeClass).to receive(:make_heavy_lifting)
    expect(SomeClass).to receive(:sleep).with(60*60)
end

this way it will only iterate through it once.

EDIT: it seems this was also suggested in the other question

Community
  • 1
  • 1
stonecrusher
  • 1,246
  • 10
  • 12