How I Learned to Stop Worrying and Love Unit Testing

What are tests for?

Who are tests for?

To all viewers but yourself, what matters is the product: the finished artwork. To you, and you alone, what matters is the process
— David Bayles & Ted Orland, Art & Fear

Protecting against bugs

Documentation


def number
 # always returns 4
 4
end
							

def number
 # always returns 4
 5
end
						

it 'always returns 4' do
 expect(number).to eq(4)
end
						

Encouraging good practices

Tests are the canary in the coal mine; when the design is bad, testing is hard.
— Sandi Metz, Practical Object-Oriented Design in Ruby

Allowing for confidence in refactor

You make good work by (among other things) making lots of work that isn't very good, and gradually weeding out the parts that aren't good
— David Bayles & Ted Orland, Art & Fear

A Good Test Suite

  • Fails when something is broken
  • Doesn't fail otherwise

Different types of tests

  • Unit
  • Integration
  • Functional
  • System

Why unit tests?

  • Easy to write
  • Easy to run
  • Easy to reason about
  • Encourage simplicity

When to write other tests

Some things you can test

  • Return values of a method
  • expect(2 + 2).to eq(4)
  • Whether other methods are called
  • Whether a job is enqueued
  • If something is truthy/falsey
  • If an exception is thrown

What is a unit test?

class Person
  def greet(name)
    name.instance_of?(String) ? "Hi #{name}!" : "Hi! Didn't catch your name."
  end
end

describe '#greet' do
  it 'contructs greeting based on string passed as name' do
    expect(Person.new.greet('Valerie')).to eq('Hello Valerie!')
  end

  it 'doesn\'t catch names for numbers' do
    expect(Person.new.greet(2)).to eq('Hi! Didn\'t catch your name.')
  end
end

What makes testing hard?

Time

  • Developer time
  • Computational time
  • The passage of time

Not knowing where to start

External systems

Go forth and conquer

LINKS