Your browser doesn’t support the features needed to display this presentation.

A simplified version of this presentation follows.

For the best experience, please use one of the following browsers:

Unit Testing with Minitest


Memphis Ruby Users Group

1/21/2013

Josh W Lewis - @joshwlewis

Plia Systems

In computer programming, unit testing is a method by which individual units of source code, sets of one or more computer program modules together with associated control data, usage procedures, and operating procedures are tested to determine if they are fit for use.
- Wikipedia

TL;DR

Unit testing is code that makes sure your code works.

Why Unit Test?

Minitest is Awesome!

github.com/seattlerb/minitest

Test/Unit style tests are standard with Minitest

class User < ActiveRecord::Base
  def initials
    (first_name[0] + middle_name[0] + last_name[0]).upcase
  end
end
class TestUser < Minitest::Test
  def setup
    @user = User.new first_name: 'Josh', middle_name: 'Wayne', 
                     last_name: 'Lewis'
  end

  def test_initials
    assert_equal @user.initials, 'JWL'
  end
end

Spec style tests are also available with Minitest

class User < ActiveRecord::Base
  def initials
    (first_name[0] + middle_name[0] + last_name[0]).upcase
  end
end
describe User do
  subject { User.new first_name: 'Josh', middle_name: 'Wayne',
                     last_name: 'Lewis' }

  describe :initials do
    it 'should return first letter of all names' do
      subject.initials.must_equal 'JWL'
    end
  end
end

Let's make an app for that...

My boss wants something to translate English to Pig Latin and Pig Latin to English. And he wants it to remember previous translations.

rails new pig_latin --database=postgresql --skip-test-unit

Source available at: github.com/joshwlewis/pig_latin

Use minitest-rails to bootstrap your test suite

Gemfile

gem 'minitest-rails', '~> 0.9.0', group: [:development, :test]
bundle install
rails generate mini_test:install

test/test_helper.rb

ENV["RAILS_ENV"] = "test"
require File.expand_path('../../config/environment', __FILE__)
require "rails/test_help"
require "minitest/rails"
# ...
bundle exec rake test

Automated testing enables TDD workflow

Gemfile

gem 'guard-minitest'

Guardfile

guard :minitest do
  watch(%r{^test/(.*)_test\.rb})
  watch(%r{^lib/(.+)\.rb})         {|m| "test/#{m[1]}_test.rb"}
  watch(%r{^test/test_helper\.rb}) {'test'}
  watch(%r{^app/(.+)\.rb})         {|m| "test/#{m[1]}_test.rb"}
  # ...
end

The Payoff...

Resources

Minitest documentation
github.com/seattlerb/minitest
Minitest Quick Reference
mattsears.com/articles/2011/12/10/minitest-quick-reference
Rails Assertions
topfunky.com/clients/rails/ruby_and_rails_assertions.pdf
Pig Latin Translator
github.com/joshwlewis/pig_latin
This Presentation
joshwlewis.com/slides/minitest