vendredi 21 décembre 2018

creating an initialize method with Kernel as a dependency to generate random numbers

I have a main class A that has an initialize method with 3 args. Another class B is inheriting class A, however I am trying to override the initialize method with Kernel in the args to generate random numbers which I can test in rspec. I want to use Kernel by means of dependency injection so that I can test it accurately.

Class A

class Person
  attr_accessor :name, :age, :teeth

  def initialize(name, age, teeth)
    @name = name
    @age = age
    @teeth = teeth
  end

  def to_s
    "#{@name}, is #{@age} years old, and has #{@teeth} teeth left"
  end
end

Class B

class OverSixity < Person

  attr_accessor :name, :age, :teeth, :kernel

  def initialize(name, age, teeth, kernel = Kernel)
    @kernel = Kernel.rand(2)
    @name = name
    @age = age
    @teeth = teeth
  end

  def next_year
    if kernel == 1
      @age += 1 and @teeth -= 1
    else 
      @age += 1
    end
  end
end

this is my test

  describe "next_year" do
    it "it randomly decreases teeth by 1" do
      person = OverSixity.new("Ben", 65, 30)
      kernel = Kernel.rand(2)
      allow(kernel).to receive(rand(2)).and_return(1)
      person.next_year
      expect(person.teeth).to eq(29)
    end

Thank you




Aucun commentaire:

Enregistrer un commentaire