Skip to content

Instantly share code, notes, and snippets.

@EliseFitz15
Last active November 8, 2015 17:54
Show Gist options
  • Save EliseFitz15/e371e6957a54e3984811 to your computer and use it in GitHub Desktop.
Save EliseFitz15/e371e6957a54e3984811 to your computer and use it in GitHub Desktop.
unit-testing-clinic

Clinic overview

In this clinic, we will go over:

  • TDD workflow
  • Setting up rspec in your projects
  • Build classes with TDD
  • Resource for good practices for writing rspec tests

##TDD workflow

  • Write tests - get a failing test suite
  • Let failing tests guide our code development
  • Do the simplest thing to get the test to pass
  • Refactor

##Getting RSpec Set Up

  • gem install rspec
  • spec file for each class file
    • In the project root set up the following file structure:
    • spec/lib/class_spec.rb
    • lib/class.rb goes in lib
  • Configure RSpec for color tests. In the root folder touch .rspec and insert "--color" "--fail-fast"
  • To reference our class tests need require_relative '../../lib/class.rb'

##Building classes with TDD Today we are going to build two objects:

  • Dice object, with state of sides and behavior of rolling.
  • Pokemon objects, with states and behavior such as name, type, ability, strength, attack etc.

So let's start with our dice class and construct this in a test driven way.

Git set up

  • git init
  • git add
  • git commit -m "initial commit"

###Start with a Test

  • Start building our first tests
    • require_relative '../lib/dice.rb'
  • Let's describe our Dice class.
    • RSpec.describe Dice do standard to start with a describe for the class/initaialize method
    • syntax class method vs. instance method
    • '.new' constructor, class method
    • '#roll' instance method
  • Let's build out our Pokemon class for our objects.
    • Think about what a character has.
    • Let's first do name... then species... equipment ... strength... hit points
    • methods equipment set to nil, load_equipment(weapon), attack!, alive?
    • introduce let and let!
  • describe, context, it blocks language best practice
    • Method definition in a describe block with ".notation" for class methods and "#notation" for instance methods
    • Context for use cases (e.g. true or false) We create a context blocks to clarify the different states we expect
    • Third step is to write an it block in which we will place our assertion about the behavior. The string of text that follows this 'it' call is simply a descriptor that explains what we expect the result of the method call to be.
  • Refactoring
    • we can refactor our tests (e.g move the let(:pokemon) up to the top to have access to all)
    • we can look back at our code and refactor methods and run the test suite to make sure it passes our intended outcomes.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment