Module: Greenbar::RandSetup

Includes:
TestSetup
Defined in:
lib/greenbar/RandSetup.rb

Overview

:startdoc:#

Purpose

Provides a way to control random numbers generated from Kernel#rand

Usage

  • Include Greenbar::RandSetup in your test case.

  • Seed sequences for each ‘max’ used in the code under test. Use seed_rand_sequence

Kernel#rand is called to generate random numbers, and it takes a single argument, ‘max’ If you’re picking a random color from a collection of eight, you might seay

color = COLORS[rand(8)]

Unfortunately, if you’re really getting random numbers back, it’s very difficult to write a test. So, you might add this call to your test case.

seed_rand_sequence 8, [2, 4]

If you call it a third time, it will return 2 again, as the sequence is repeated automatically.

Example

:include: doc/examples/RandSetup.rb

Constant Summary collapse

RAND_SEQUENCES =
{}

Instance Method Summary collapse

Methods included from TestSetup

included, #setup, #setup_mixins, #teardown, #teardown_mixins

Instance Method Details

#seed_rand_sequence(max, sequence) ⇒ Object

and the sequence is rotated, appending this return to the end.



71
72
73
74
75
# File 'lib/greenbar/RandSetup.rb', line 71

def seed_rand_sequence(max, sequence)
  array = sequence.to_a
  raise "Must provide a non-empty sequence." if array.empty?
  RAND_SEQUENCES[max] = array
end

#setup_mixinObject



45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/greenbar/RandSetup.rb', line 45

def setup_mixin
  Kernel.class_eval do
    
    alias :rand_saved_by_RandSetup :rand
    
    def rand(max=0)
      raise "Must use seed_rand_sequence(#{max}) before using rand(#{max})." unless RAND_SEQUENCES.has_key? max
      RAND_SEQUENCES[max] << RAND_SEQUENCES[max].shift
      RAND_SEQUENCES[max][-1]
    end
  end
end

#teardown_mixinObject



58
59
60
61
62
63
64
# File 'lib/greenbar/RandSetup.rb', line 58

def teardown_mixin
  Kernel.class_eval do
    alias :rand :rand_saved_by_RandSetup
    remove_method :rand_saved_by_RandSetup
    RAND_SEQUENCES.clear
  end
end