Skip to content

Instantly share code, notes, and snippets.

@jimweirich
Last active December 14, 2015 02:58
Show Gist options
  • Save jimweirich/5017243 to your computer and use it in GitHub Desktop.
Save jimweirich/5017243 to your computer and use it in GitHub Desktop.
Bowling kata tests (one version at least)
class Bowling
def score_rolls(rolls)
init_rolls(rolls)
score = 0
frame = 0
while frame < 10
if strike?
score += sum_of_next_rolls(3)
consume(1)
elsif spare?
score += sum_of_next_rolls(3)
consume(2)
else
score += sum_of_next_rolls(2)
consume(2)
end
frame += 1
end
score
end
private
def strike?
first_roll == 10
end
def spare?
first_roll + second_roll == 10
end
def init_rolls(rolls)
@rolls = rolls.dup
end
def consume(n)
n.times { @rolls.shift }
end
def sum_of_next_rolls(n)
(0...n).inject(0) { |acc, v| acc + @rolls[v] }
end
def first_roll
@rolls[0]
end
def second_roll
@rolls[1]
end
end
require 'rspec/given'
require 'bowling'
class Integer
def rolls_of(value)
[value] * self
end
end
RSpec::Given.use_natural_assertions
describe Bowling do
Given(:rolls) { 20.rolls_of(0) }
Given(:game) { Bowling.new }
When(:result) { game.score_rolls(rolls) }
context "when I roll all zeros" do
Then { result == 0 }
end
context "when I roll all ones" do
Given(:rolls) { 20.rolls_of(1) }
Then { result == 20 }
end
context "when I roll a spare followed by a 3" do
Given(:rolls) { [3, 7, 3] + 17.rolls_of(0) }
Then { result == 16 }
end
context "when I roll a strike" do
Given(:rolls) { [ 10, 3, 4 ] + 17.rolls_of(0) }
Then { result == 24 }
end
context "when I roll all strikes" do
Given(:rolls) { 12.rolls_of(10) }
Then { result == 300 }
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment