I had a cool experience writing tests for my blackjack game! below I'll include the code, with the tests I wrote following them, and a little reflection after each pair.
card.rb FILE:
class Card
attr_accessor :suite, :rank
def initialize(suite, rank)
@rank = rank
@suite = suite
end
def face_card?
['j', 'q', 'k'].include?(@rank)
end
end
card.rb passing TESTS:
require 'spec_helper'
RSpec.describe Card do
let(:card) {card = Card.new("club", 10)}
describe '.new' do
it "takes a suite and rank as arguments" do
expect(card).to be_a(Card)
end
end
describe "#suite" do
it "returns a suite" do
expect(card.suite).to eq("club")
expect(card.suite).not_to eq("spade")
end
end
describe "#rank" do
it "returns a rank" do
expect(card.rank).to eq(10)
expect(card.rank).not_to eq(11)
end
end
describe "#face_card?" do
card2 = Card.new("club", 'j')
it "tells you if you have a facecard" do
expect(card2.face_card?).to eq(TRUE)
expect(card.face_card?).to eq(FALSE)
end
end
comments:
This one was definitely the easiest because I was basically just testing to see if the card was a card. notable thing I wrote that I've never done before was a test that looked at a boolean. I also played around with writing the "not to equal" sort of negative tests. Also, I'd say hooking everything up to my spec helper was interesting.
deck.rb FILE:
class Deck
attr_accessor :deck_o_cards, :deal
def initialize
suites = ['clubs','hearts','spades', 'diamonds']
ranks = ['a', 2, 3, 4,5,6,7,8,9,10,'j', 'q', 'k']
@deck_o_cards = []
suites.each do |suite|
ranks.each do |rank|
@deck_o_cards << Card.new(suite,rank)
end
end
@deck_o_cards.shuffle!
end
def deal
dealt_card = @deck_o_cards.pop
end
end
deck.rb PASSING TESTS:
require 'spec_helper'
RSpec.describe Deck do
let(:deck) {deck = Deck.new}
describe ".new" do
it "makes a deck" do
expect(deck).to be_a(Deck)
end
end
describe "#deck_o_cards" do
it "stores 52 cards in an array" do
expect(deck.deck_o_cards.length).to eq(52)
end
end
describe "deal" do
it "takes the last card and returns it" do
expect(deck.deal).to be_a(Card)
end
end
end
comments: so this one was interesting because 'deck o cards' was an array, right? and I really had to know that and to know that it had 52 cards in it, which meant I really had to understand my "suites.each do" "ranks.each do" nested loop to understand how to write the test in a useful way. It was hard to test a random object, right? so I could only test and see that a card was indeed there rather than trying to anticipate what that card actually was.
hand.rb FILE: