Click here to load reader
Upload
lvrubygroup
View
666
Download
1
Embed Size (px)
DESCRIPTION
Citation preview
Unit Testing
Programming Ruby 1.9Chapter 13
What is it?
●testing at the lowest level●individual methods or lines
within methods
Why?
●less "archaeology"●decoupled designs
●peace of mind when refactoring
MiniTest::Unit vs Test::Unit
require 'minitest/unit'● MiniTest new in 1.9 "a little leaner"● has a compatibility layer for Test::Unit● negative assertions renamed to refute
○ assert_not_nil -> refute_nil● missing assertions
○ assert_not_raises○ assert_not_throws
require 'test/unit'● most of the features people used
gem install test-unit● little used features: test cases, GUI runners
Example Test
require_relative 'romanbug'require 'test/unit'
class TestRoman < Test::Unit::TestCase def test_simple assert_equal "i", Roman.new(1).to_s assert_equal "ix", Roman.new(9).to_s endend
Structuring Tests
● prefix methods with test_● setup/teardown run before/after each test
○ use passed? in teardown to see if the test passed
Running Tests (files in the same folder)
● ruby test_roman.rb○ Kernel::at_exit
● ruby test_roman.rb -n test_simple● ruby test_roman.rb -n /simple/
Organizing tests
roman/ lib/ roman.rb other files....
test/ test_roman.rb other tests.... other files....
Running Tests (standard structure)
● ruby -I path/to/app/lib path/to/app/test/test_roman.rb
● ruby -I lib test/test_roman.rb
RSpec
● write story before writing tests● special .should semantics
RSpec Example
require_relative 'tennis_scorer'
describe TennisScorer do it "should start with a score of 0-0" do ts = TennisScorer.new ts.score.should == "0-0" end it "should be 15-0 if the server wins a point"end
RSpec
before(:each), before(:all), after(:each), after(:all)
Shoulda
● less opinionated than RSpec● code lives inside Test::Unit::TestCases● makes test cases, so Test::Unit assertions work
Shoulda Example
require 'test/unit'require 'shoulda'require_relative 'tennis_scorer.rb'
class TennisScorerTest < Test::Unit::TestCase context "Tennis scores" do setup do @ts = TennisScorer.new end should "start with a score of 0-0" do assert_equal("0-0", @ts.score) end endend
Shoulda
● contexts may be nested● setup, should, should_eventually, teardown
End