Rabbit Slide Show

Self-testing Code in Ruby

2017-10-16

Description

This talk explains the concept of self-testing code with practices in ruby using rspec.

Text

Page: 1

Self-testing Code in
Ruby
Giovanni Sakti
Starqle

Page: 2

What is Self-testing code?

Page: 3

Self-testing code
Code that have built-in tests
The tests serve as a binding contract
The tests can be run arbitrarily

Page: 4

What is TDD? How it differs from self-
testing code?

Page: 5

TDD
Practices of writing tests before the
code
Ensure that the code is self-tested
It is, however, optional to do TDD to
write self-testing code

Page: 6

TDD
But some companies enforce TDD
because TDD enforces YAGNI principle

Page: 7

TDD
We'll see why...

Page: 8

TDD Steps
Write a test
Run the test, it should fail
Write code just enough to pass the
test
Run the test
Repeat

Page: 9

TDD & YAGNI
Because we only write just enough code
to pass the test, there will be no
unnecessary codes

Page: 10

Test in Ruby
There are several tools for doing testing
in ruby

Page: 11

Test in Ruby
RSpec
Minitest
test-unit

Page: 12

Test in Ruby
Let's try using RSpec

Page: 13

RSpec Install
% gem install rspec

Page: 14

RSpec Help
% rspec --help

Page: 15

Now let's do TDD practice using RSpec

Page: 16

TDD with RSpec (1)
Create a simple test of program that we
want to create
# game_spec.rb
RSpec.describe Game do
describe "#score" do
it "returns 0 for new game" do
game = Game.new
expect(game.score).to eq(0)
end
end
end

Page: 17

TDD with RSpec (2)
Run the example and watch it fail
% rspec game_spec.rb
uninitialized constant Object::Game (NameError)

Page: 18

TDD with RSpec (3)
Now write just enough code to make it
pass
# game.rb
class Game
attr_reader :score
def initialize
@score = 0
end
end

Page: 19

TDD with RSpec (3)
Now write just enough code to make it
pass
# game_spec.rb
require './game'
...

Page: 20

TDD with RSpec (4)
Run the example and the test shall pass
% rspec game_spec.rb --color --format doc
Game
#score
returns 0 for all gutter game
Finished in 0.00057 seconds
1 example, 0 failures

Page: 21

TDD with RSpec (5)
Repeat with new features

Page: 22

Thanks

Other slides