Skip to content

Instantly share code, notes, and snippets.

@moonglum
Created September 4, 2017 18:47
Show Gist options
  • Save moonglum/f763eb257a4ede22e3008d861225535c to your computer and use it in GitHub Desktop.
Save moonglum/f763eb257a4ede22e3008d861225535c to your computer and use it in GitHub Desktop.
class CookieJar
def initialize(initial_count)
@count = initial_count
end
def count_cookies
@count
end
def remove_cookies(amount)
raise CookieOutOfBoundsException.new if amount > @count
@count -= amount
end
def add_cookies(amount)
@count += amount
end
end
class Kitten
def initialize(cookie_jar)
@cookie_jar = cookie_jar
end
def eat_cookie
@cookie_jar.remove_cookies(1)
end
end
class Grandma
def initialize(cookie_jar)
@cookie_jar = cookie_jar
end
def bake_cookies(amount)
@cookie_jar.add_cookies(amount)
end
end
class CookieMonster
def initialize(cookie_jar)
@cookie_jar = cookie_jar
end
def eat_cookies(amount)
@cookie_jar.remove_cookies(amount)
end
end
class CookieOutOfBoundsException < RangeError
end
require_relative "cookies"
describe "the workflow" do
it "should end in a CookieOutOfBounds Exception" do
cookie_jar = CookieJar.new(5)
kitten = Kitten.new(cookie_jar)
grandma = Grandma.new(cookie_jar)
cookie_monster = CookieMonster.new(cookie_jar)
kitten.eat_cookie
kitten.eat_cookie
grandma.bake_cookies(5)
cookie_monster.eat_cookies(5)
expect { cookie_monster.eat_cookies(10) }.to raise_error(CookieOutOfBoundsException)
end
end
describe CookieJar do
subject { CookieJar.new(3) }
it "should be able to count the cookies within" do
expect(subject.count_cookies).to be 3
end
it "should be able to remove cookies" do
expect { subject.remove_cookies(2) }.to change { subject.count_cookies }.from(3).to(1)
end
it "should be able to add cookies" do
expect { subject.add_cookies(5) }.to change { subject.count_cookies }.from(3).to(8)
end
it "should raise a CookieOutOfBoundsException when containg less than 0 cookies" do
expect { subject.remove_cookies(4) }.to raise_error(CookieOutOfBoundsException)
end
end
describe Kitten do
subject { Kitten.new(cookie_jar) }
let(:cookie_jar) { instance_double(CookieJar) }
it "should eat a single cookie" do
expect(cookie_jar).to receive(:remove_cookies).with(1)
subject.eat_cookie
end
end
describe Grandma do
subject { Grandma.new(cookie_jar) }
let(:cookie_jar) { instance_double(CookieJar) }
it "should add cookies to the jar after baking them" do
expect(cookie_jar).to receive(:add_cookies).with(5)
subject.bake_cookies(5)
end
end
describe CookieMonster do
subject { CookieMonster.new(cookie_jar) }
let(:cookie_jar) { instance_double(CookieJar) }
it "should eat multiple cookies from the jar" do
expect(cookie_jar).to receive(:remove_cookies).with(7)
subject.eat_cookies(7)
end
end
# frozen_string_literal: true
source "https://rubygems.org"
gem "rspec"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment