Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
712 views
in Technique[技术] by (71.8m points)

ruby on rails - What is the best practice when it comes to testing "infinite loops"?

My basic logic is to have an infinite loop running somewhere and test it as best as possible. The reason for having an infinite loop is not important (main loop for games, daemon-like logic...) and I'm more asking about best practices regarding a situation like that.

Let's take this code for example:

module Blah
  extend self

  def run
     some_initializer_method
     loop do
        some_other_method
        yet_another_method
     end
  end
end

I want to test the method Blah.run using Rspec (also I use RR, but plain rspec would be an acceptable answer).

I figure the best way to do it would be to decompose a bit more, like separating the loop into another method or something:

module Blah
  extend self

  def run
     some_initializer_method
     do_some_looping
  end

 def do_some_looping
   loop do
     some_other_method
     yet_another_method
   end
 end
end

... this allows us to test run and mock the loop... but at some point the code inside the loop needs to be tested.

So what would you do in such a situation?

Simply not testing this logic, meaning test some_other_method & yet_another_method but not do_some_looping ?

Have the loop break at some point via a mock?

... something else?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

What might be more practical is to execute the loop in a separate thread, assert that everything is working correctly, and then terminate the thread when it is no longer required.

thread = Thread.new do
  Blah.run
end

assert_equal 0, Blah.foo

thread.kill

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...