100% found this document useful (3 votes)
277 views

Download Test Driven Development in Ruby A Practical Introduction to TDD Using Problem and Solution Domain Analysis Paranj ebook All Chapters PDF

TDD

Uploaded by

reinikriegze
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (3 votes)
277 views

Download Test Driven Development in Ruby A Practical Introduction to TDD Using Problem and Solution Domain Analysis Paranj ebook All Chapters PDF

TDD

Uploaded by

reinikriegze
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 55

Download the Full Version of textbook for Fast Typing at textbookfull.

com

Test Driven Development in Ruby A Practical


Introduction to TDD Using Problem and Solution
Domain Analysis Paranj

https://textbookfull.com/product/test-driven-development-in-
ruby-a-practical-introduction-to-tdd-using-problem-and-
solution-domain-analysis-paranj/

OR CLICK BUTTON

DOWNLOAD NOW

Download More textbook Instantly Today - Get Yours Now at textbookfull.com


Recommended digital products (PDF, EPUB, MOBI) that
you can download immediately if you are interested.

Test Driven Java Development Invoke TDD principles for end


to end application development 2nd Edition Alex Garcia

https://textbookfull.com/product/test-driven-java-development-invoke-
tdd-principles-for-end-to-end-application-development-2nd-edition-
alex-garcia/
textboxfull.com

Domain-Driven Laravel: Learn to Implement Domain-Driven


Design Using Laravel Jesse Griffin

https://textbookfull.com/product/domain-driven-laravel-learn-to-
implement-domain-driven-design-using-laravel-jesse-griffin/

textboxfull.com

iOS Test Driven Development by Tutorials First Edition


Learn Real World Test Driven Development Joshua Greene

https://textbookfull.com/product/ios-test-driven-development-by-
tutorials-first-edition-learn-real-world-test-driven-development-
joshua-greene/
textboxfull.com

Test-Driven Development in Go: A practical guide to


writing idiomatic and efficient Go tests through real-
world example 1st Edition Adelina Simion
https://textbookfull.com/product/test-driven-development-in-go-a-
practical-guide-to-writing-idiomatic-and-efficient-go-tests-through-
real-world-example-1st-edition-adelina-simion/
textboxfull.com
Practical Test Automation: Learn to Use Jasmine, RSpec,
and Cucumber Effectively for Your TDD and BDD Panos
Matsinopoulos
https://textbookfull.com/product/practical-test-automation-learn-to-
use-jasmine-rspec-and-cucumber-effectively-for-your-tdd-and-bdd-panos-
matsinopoulos/
textboxfull.com

Matlab A Practical Introduction to Programming and Problem


Solving Stormy Attaway

https://textbookfull.com/product/matlab-a-practical-introduction-to-
programming-and-problem-solving-stormy-attaway/

textboxfull.com

MATLAB A Practical Introduction to Programming and Problem


Solving Stormy Attaway

https://textbookfull.com/product/matlab-a-practical-introduction-to-
programming-and-problem-solving-stormy-attaway-2/

textboxfull.com

Python Testing Cookbook Easy solutions to test your Python


projects using test driven development and Selenium 2nd
Edition Greg L. Turnquist & Bhaskar N. Das
https://textbookfull.com/product/python-testing-cookbook-easy-
solutions-to-test-your-python-projects-using-test-driven-development-
and-selenium-2nd-edition-greg-l-turnquist-bhaskar-n-das/
textboxfull.com

Practical Domain-Driven Design in Enterprise Java - Using


Jakarta EE, Eclipse MicroProfile, Spring Boot, and the
Axon Framework 1st Edition Vijay Nair
https://textbookfull.com/product/practical-domain-driven-design-in-
enterprise-java-using-jakarta-ee-eclipse-microprofile-spring-boot-and-
the-axon-framework-1st-edition-vijay-nair/
textboxfull.com
Test Driven
Development
in Ruby
A Practical Introduction to TDD Using
Problem and Solution Domain Analysis

Bala Paranj
Test Driven
Development in Ruby
A Practical Introduction to TDD Using
Problem and Solution Domain Analysis

Bala Paranj
Test Driven Development in Ruby: A Practical Introduction to TDD Using Problem and Solution
Domain Analysis
Bala Paranj
Atlanta, Georgia, USA
ISBN-13 (pbk): 978-1-4842-2637-7 ISBN-13 (electronic): 978-1-4842-2638-4
DOI 10.1007/978-1-4842-2638-4
Library of Congress Control Number: 2017934648
Copyright © 2017 by Bala Paranj
This work is subject to copyright. All rights are reserved by the Publisher, whether the whole or part of the
material is concerned, specifically the rights of translation, reprinting, reuse of illustrations, recitation,
broadcasting, reproduction on microfilms or in any other physical way, and transmission or information
storage and retrieval, electronic adaptation, computer software, or by similar or dissimilar methodology now
known or hereafter developed.
Trademarked names, logos, and images may appear in this book. Rather than use a trademark symbol with
every occurrence of a trademarked name, logo, or image we use the names, logos, and images only in an
editorial fashion and to the benefit of the trademark owner, with no intention of infringement of the trademark.
The use in this publication of trade names, trademarks, service marks, and similar terms, even if they are
not identified as such, is not to be taken as an expression of opinion as to whether or not they are subject to
proprietary rights.
While the advice and information in this book are believed to be true and accurate at the date of publication,
neither the authors nor the editors nor the publisher can accept any legal responsibility for any errors or
omissions that may be made. The publisher makes no warranty, express or implied, with respect to the material
contained herein.
Managing Director: Welmoed Spahr
Editorial Director: Todd Green
Acquisitions Editor: Steve Anglin
Development Editor: Matthew Moodie
Technical Reviewer: Ronald Petty
Coordinating Editor: Mark Powers
Copy Editor: April Rondeau
Compositor: SPi Global
Indexer: SPi Global
Artist: SPi Global
Cover image designed by Freepik.
Distributed to the book trade worldwide by Springer Science+Business Media New York,
233 Spring Street, 6th Floor, New York, NY 10013. Phone 1-800-SPRINGER, fax (201) 348-4505, e-mail
[email protected], or visit www.springeronline.com. Apress Media, LLC is a California LLC
and the sole member (owner) is Springer Science + Business Media Finance Inc (SSBM Finance Inc). SSBM
Finance Inc is a Delaware corporation.
For information on translations, please e-mail [email protected], or visit http://www.apress.com/
rights-permissions.
Apress titles may be purchased in bulk for academic, corporate, or promotional use. eBook versions and
licenses are also available for most titles. For more information, reference our Print and eBook Bulk Sales web
page at www.apress.com/bulk-sales.
Any source code or other supplementary material referenced by the author in this book is available to
readers on GitHub via the book's product page, located at www.apress.com/9781484226377. For more
detailed information, please visit http://www.apress.com/source-code.
Printed on acid-free paper
This book is dedicated to the memory of my father.
Contents at a Glance

About the Author��������������������������������������������������������������������������������������������������� xiii


About the Technical Reviewer���������������������������������������������������������������������������������xv
Foreword���������������������������������������������������������������������������������������������������������������xvii
Acknowledgments��������������������������������������������������������������������������������������������������xix
Introduction������������������������������������������������������������������������������������������������������������xxi


■Chapter 1: The Basics�������������������������������������������������������������������������������������������� 1

■Chapter 2: Katas�������������������������������������������������������������������������������������������������� 57

■Chapter 3: Techniques in TDD���������������������������������������������������������������������������� 125

■Chapter 4: Importance of Test Cases����������������������������������������������������������������� 153

■Chapter 5: Character-to-Number Conversion���������������������������������������������������� 163

■Chapter 6: Conway’s Game of Life��������������������������������������������������������������������� 171

■Chapter 7: Gilded Rose�������������������������������������������������������������������������������������� 221

■Chapter 8: Dealing with Third-Party APIs���������������������������������������������������������� 263

■Chapter 9: Pair Ranking������������������������������������������������������������������������������������ 277

Index��������������������������������������������������������������������������������������������������������������������� 285

v
Contents

About the Author��������������������������������������������������������������������������������������������������� xiii


About the Technical Reviewer���������������������������������������������������������������������������������xv
Foreword���������������������������������������������������������������������������������������������������������������xvii
Acknowledgments��������������������������������������������������������������������������������������������������xix
Introduction������������������������������������������������������������������������������������������������������������xxi


■Chapter 1: The Basics�������������������������������������������������������������������������������������������� 1
Terminology���������������������������������������������������������������������������������������������������������������������� 1
Kata�������������������������������������������������������������������������������������������������������������������������������������������������������� 1
Coding Kata�������������������������������������������������������������������������������������������������������������������������������������������� 2
Domain��������������������������������������������������������������������������������������������������������������������������������������������������� 2
Problem Domain������������������������������������������������������������������������������������������������������������������������������������� 2
Solution Domain������������������������������������������������������������������������������������������������������������������������������������� 2
Domain Expert���������������������������������������������������������������������������������������������������������������������������������������� 2
Domain Knowledge��������������������������������������������������������������������������������������������������������������������������������� 3

Defining the Problem Domain and the Solution Domain�������������������������������������������������� 3


Learning TDD ������������������������������������������������������������������������������������������������������������������� 3
Learning by Coding Kata������������������������������������������������������������������������������������������������������������������������� 3
Learning Retrospective��������������������������������������������������������������������������������������������������������������������������� 4
Intent vs. Implementation������������������������������������������������������������������������������������������������ 4
Intent������������������������������������������������������������������������������������������������������������������������������������������������������ 4
Implementation��������������������������������������������������������������������������������������������������������������������������������������� 4
Intent and Implementation��������������������������������������������������������������������������������������������������������������������� 4
Separate Intent from Implementation����������������������������������������������������������������������������������������������������� 7

vii
■ Contents

Tests Are Executable Documentation��������������������������������������������������������������������������������������������������� 11


Shift in Mental State����������������������������������������������������������������������������������������������������������������������������� 11

Overview of TDD������������������������������������������������������������������������������������������������������������� 12
Test Driven Development���������������������������������������������������������������������������������������������������������������������� 12
The Five Steps of TDD��������������������������������������������������������������������������������������������������������������������������� 13
Separation of Intent from Implementation�������������������������������������������������������������������������������������������� 16
Ping Pong Pair Programming Technique���������������������������������������������������������������������������������������������� 16
Black Box Perspective�������������������������������������������������������������������������������������������������������������������������� 16
Shift in System and Mental States������������������������������������������������������������������������������������������������������� 17
Importance of Discipline����������������������������������������������������������������������������������������������������������������������� 18
Overcoming Difficulty �������������������������������������������������������������������������������������������������������������������������� 18

Problem-Solving Skills��������������������������������������������������������������������������������������������������� 18
Four Phases of Problem Solving����������������������������������������������������������������������������������������������������������� 19
Subskills of Test Driven Development�������������������������������������������������������������������������������������������������� 20
Alternative Representations����������������������������������������������������������������������������������������������������������������� 25
Divide and Conquer Strategy���������������������������������������������������������������������������������������������������������������� 26

Designing Test Cases����������������������������������������������������������������������������������������������������� 26


Sum a List of Numbers������������������������������������������������������������������������������������������������������������������������� 26
Sequence of Test Cases������������������������������������������������������������������������������������������������������������������������ 27

Assertion������������������������������������������������������������������������������������������������������������������������ 28
Test Driving Calculator��������������������������������������������������������������������������������������������������� 30
Canonical Test Structure����������������������������������������������������������������������������������������������������������������������� 30
Arrange, Act, Assert������������������������������������������������������������������������������������������������������������������������������ 30
Calculator��������������������������������������������������������������������������������������������������������������������������������������������� 31
Subtraction������������������������������������������������������������������������������������������������������������������������������������������� 34

Common Mistakes���������������������������������������������������������������������������������������������������������� 37
Common Mistakes in the TDD Cycle����������������������������������������������������������������������������������������������������� 37
Base Conversion����������������������������������������������������������������������������������������������������������������������������������� 38
Code Reflecting Test Data��������������������������������������������������������������������������������������������������������������������� 46
Multiple Assertions������������������������������������������������������������������������������������������������������������������������������� 47

viii
■ Contents

Forgetting to Test the Negative Case���������������������������������������������������������������������������������������������������� 50


Not Testing the Boundary Conditions���������������������������������������������������������������������������������������������������� 50
Not Updating the Tests�������������������������������������������������������������������������������������������������������������������������� 50
Implementation-Aware Tests���������������������������������������������������������������������������������������������������������������� 53

Summary������������������������������������������������������������������������������������������������������������������������ 54

■Chapter 2: Katas�������������������������������������������������������������������������������������������������� 57
Fibonacci Sequence������������������������������������������������������������������������������������������������������� 57
Problem Statement������������������������������������������������������������������������������������������������������������������������������� 58
Problem Domain Analysis��������������������������������������������������������������������������������������������������������������������� 58
Solution Domain Analysis��������������������������������������������������������������������������������������������������������������������� 59
Assumptions����������������������������������������������������������������������������������������������������������������������������������������� 62
Test-Driven Fibonacci��������������������������������������������������������������������������������������������������������������������������� 62

Fizz Buzz������������������������������������������������������������������������������������������������������������������������ 71
Problem Statement������������������������������������������������������������������������������������������������������������������������������� 71
Problem Domain Analysis��������������������������������������������������������������������������������������������������������������������� 71
Solution Domain Analysis��������������������������������������������������������������������������������������������������������������������� 72
Test-Driven FizzBuzz���������������������������������������������������������������������������������������������������������������������������� 72
No if-else Constraint����������������������������������������������������������������������������������������������������������������������������� 77
No if Constraint������������������������������������������������������������������������������������������������������������������������������������� 86
Implementation-Independent Tests������������������������������������������������������������������������������������������������������ 88
Crossing the System Boundary������������������������������������������������������������������������������������������������������������ 90
Mocking as a Design Technique����������������������������������������������������������������������������������������������������������� 90
Abstraction Levels in a System������������������������������������������������������������������������������������������������������������ 94
Testing Random Behavior��������������������������������������������������������������������������������������������������������������������� 95
Testing Time-Dependent Behavior�������������������������������������������������������������������������������������������������������� 96
Simulating User Input��������������������������������������������������������������������������������������������������������������������������� 97
Open Closed Principle������������������������������������������������������������������������������������������������������������������������� 100
Difference Reduction�������������������������������������������������������������������������������������������������������������������������� 102
Defect Localization����������������������������������������������������������������������������������������������������������������������������� 104

ix
■ Contents

Stack���������������������������������������������������������������������������������������������������������������������������� 105
Basic Stack����������������������������������������������������������������������������������������������������������������������������������������� 105
Test Precisely and Concretely������������������������������������������������������������������������������������������������������������� 107
Make Your Code Robust���������������������������������������������������������������������������������������������������������������������� 109

The Sieve of Eratosthenes�������������������������������������������������������������������������������������������� 112


Algorithm�������������������������������������������������������������������������������������������������������������������������������������������� 114

Prime Factors��������������������������������������������������������������������������������������������������������������� 119


Problem Statement����������������������������������������������������������������������������������������������������������������������������� 119
Problem Domain Analysis������������������������������������������������������������������������������������������������������������������� 119
Solution Domain Analysis������������������������������������������������������������������������������������������������������������������� 120

Summary���������������������������������������������������������������������������������������������������������������������� 124

■Chapter 3: Techniques in TDD���������������������������������������������������������������������������� 125
Obvious Implementation���������������������������������������������������������������������������������������������� 125
Fake It Till You Make It�������������������������������������������������������������������������������������������������� 127
Triangulation����������������������������������������������������������������������������������������������������������������� 129
Addition���������������������������������������������������������������������������������������������������������������������������������������������� 129
Sum a List of Numbers����������������������������������������������������������������������������������������������������������������������� 130

Solution Domain Analysis Redux���������������������������������������������������������������������������������� 135


Reduction��������������������������������������������������������������������������������������������������������������������� 136
Problem Statement����������������������������������������������������������������������������������������������������������������������������� 137
Steps to Solve the Problem���������������������������������������������������������������������������������������������������������������� 137
Test-Driven GCD���������������������������������������������������������������������������������������������������������������������������������� 139

Transformation Priority Premise����������������������������������������������������������������������������������� 142


Refactorings and Transformations������������������������������������������������������������������������������������������������������ 143
Transformation List����������������������������������������������������������������������������������������������������������������������������� 143
Counter����������������������������������������������������������������������������������������������������������������������������������������������� 144
Factorial���������������������������������������������������������������������������������������������������������������������������������������������� 149

Summary���������������������������������������������������������������������������������������������������������������������� 152

x
■ Contents


■Chapter 4: Importance of Test Cases����������������������������������������������������������������� 153
Problem Statement������������������������������������������������������������������������������������������������������ 153
Problem Domain Analysis��������������������������������������������������������������������������������������������� 153
Solution Domain Analysis��������������������������������������������������������������������������������������������� 153
Algorithm Description��������������������������������������������������������������������������������������������������� 156
Code����������������������������������������������������������������������������������������������������������������������������� 156
Summary���������������������������������������������������������������������������������������������������������������������� 162

■Chapter 5: Character-to-Number Conversion���������������������������������������������������� 163
Problem Statement������������������������������������������������������������������������������������������������������ 163
Discussion������������������������������������������������������������������������������������������������������������������������������������������ 163

Solution Domain Analysis��������������������������������������������������������������������������������������������� 163


Test Cases�������������������������������������������������������������������������������������������������������������������� 165
Summary���������������������������������������������������������������������������������������������������������������������� 169

■Chapter 6: Conway’s Game of Life��������������������������������������������������������������������� 171
Problem Statement������������������������������������������������������������������������������������������������������ 171
Problem Domain Analysis��������������������������������������������������������������������������������������������� 171
Assumptions��������������������������������������������������������������������������������������������������������������������������������������� 176

Solution Domain Analysis��������������������������������������������������������������������������������������������� 176


Moore Neighborhood�������������������������������������������������������������������������������������������������������������������������� 176

Test Cases�������������������������������������������������������������������������������������������������������������������� 177


Test-Driven Game of Life���������������������������������������������������������������������������������������������� 177
Application Statement������������������������������������������������������������������������������������������������������������������������ 209
Refactor Solution�������������������������������������������������������������������������������������������������������������������������������� 210

Code Review����������������������������������������������������������������������������������������������������������������� 214


Summary���������������������������������������������������������������������������������������������������������������������� 220

■Chapter 7: Gilded Rose�������������������������������������������������������������������������������������� 221
Form vs. Structure������������������������������������������������������������������������������������������������������� 221
Problem Statement������������������������������������������������������������������������������������������������������ 222

xi
■ Contents

Initial Setup������������������������������������������������������������������������������������������������������������������ 223


Form��������������������������������������������������������������������������������������������������������������������������������������������������� 225
Structure��������������������������������������������������������������������������������������������������������������������������������������������� 226
DeMorgan’s Laws������������������������������������������������������������������������������������������������������������������������������� 244
Making Temporal Dependency Explicit����������������������������������������������������������������������������������������������� 245
Improving the Structure���������������������������������������������������������������������������������������������������������������������� 248
Express Intent������������������������������������������������������������������������������������������������������������������������������������� 249
Tell-Don’t-Ask Principle���������������������������������������������������������������������������������������������������������������������� 252
Inheritance������������������������������������������������������������������������������������������������������������������������������������������ 255

Implementing the New Feature������������������������������������������������������������������������������������ 257


Express Domain Concepts������������������������������������������������������������������������������������������������������������������ 258

Retrospective��������������������������������������������������������������������������������������������������������������� 261
Summary���������������������������������������������������������������������������������������������������������������������� 262

■Chapter 8: Dealing with Third-Party APIs���������������������������������������������������������� 263
Subscription Plan��������������������������������������������������������������������������������������������������������� 263
Create a Plan�������������������������������������������������������������������������������������������������������������������������������������� 263
Delete a Plan�������������������������������������������������������������������������������������������������������������������������������������� 264

Stripe Customer����������������������������������������������������������������������������������������������������������� 264


Subscribe a Customer to a Plan����������������������������������������������������������������������������������� 265
Test-Driven Stripe Library�������������������������������������������������������������������������������������������� 266
Integration Tests��������������������������������������������������������������������������������������������������������������������������������� 266
Unit Tests�������������������������������������������������������������������������������������������������������������������������������������������� 268

Make Your Code Robust����������������������������������������������������������������������������������������������� 274


Summary���������������������������������������������������������������������������������������������������������������������� 276

■Chapter 9: Pair Ranking������������������������������������������������������������������������������������ 277
Problem Domain Analysis��������������������������������������������������������������������������������������������� 277
Solution������������������������������������������������������������������������������������������������������������������������ 278
Summary���������������������������������������������������������������������������������������������������������������������� 284

Index��������������������������������������������������������������������������������������������������������������������� 285

xii
About the Author

Bala Paranj has a master’s degree in electrical engineering from Wichita


State University. He has been working in the software industry since 1996.
He started his career as a technical support engineer and later became a
web developer. He most commonly uses Perl, Java, and Ruby. He has
consulted for companies in the United States, Australia, and Jamaica in
finance, telecommunications, and other domains.
He is the founder of the developer training company rubyplus.com.
He publishes podcasts and screencasts in Ruby. He has been organizing
Ruby, Rails and TDD related events since 2007. He also has developed
several open-source gems that were extracted from his side projects.
He lives in Los Altos Hills, California, with his girlfriend and his dog,
Chico. He enjoys hiking, tennis, and tango. You can buy the TDD in Ruby
course at https://rubyplus.com/sales/new?id=11
You can contact the author with any questions about his book at
[email protected].

xiii
About the Technical Reviewer

Ronald Petty, M.B.A., M.S. is the founder of Minimum Distance LLC, a


management consulting firm based in San Francisco. He spends his time
helping technology-based startups do the right thing. He is also an
instructor at UC Berkeley Extension.

xv
Foreword

I have known Bala for more than a decade. In all this time, he has consistently been a leader in the Ruby
community in the San Francisco Bay Area. Bala has mentored many Ruby and Rails developers, including
me. He is very approachable and has a very appealing style of conversation.
Case in point, last week I was waiting for him at the Starbucks near Google’s HQ in Mountain View to
get his opinions on a project I am working on. While I waited, I met a fellow coffee enthusiast who, upon
finding out that I work for Intuit (the TurboTax company), asked me for some career advice. Ten minutes
later, Bala walked in. After a quick introduction to what we were talking about, Bala took the lead on the
mentoring. No more than a minute had passed before the protégé said, “Can I please record this?” Yes, Bala
is that impressive!
Bala thinks differently. He is a genius. In fact, when the above conversation was done, the protégé asked
us for our contact information. Whereas I proceeded to enter my name, number, and email into his phone,
Bala said, “Just go to my website and click on download vCard. Boom.”
Bala’s excellence in communicating rather abstract concepts clearly and concisely is very clear in the
way the lessons and examples are laid out in this book. He builds up the examples one step at a time so that
it is crystal clear what he intends you to learn. He uses various techniques to make sure the concepts stick in
your mind.
My two key takeaways from this book are as follows:
1.
Understanding the problem is the most important part of solving the problem.
2.
Test Driven Development does not magically result in a good design. There is
more to design than just reducing duplication in code.
This is an excellent book, and I highly recommend that you read it if you plan to create great software.

—John Varghese
Devops Evangelist at Intuit

xvii
Acknowledgments

My first thanks go to Steve Anglin, who approached me with the idea of writing a Ruby book. As a first-time
author, I was both petrified and excited at the same time. He was very understanding about my situation and
provided me the freedom to choose the topic and timing of the book.
I would like to thank Rhonda Jezek for pairing with me on most of the examples in this book, and Daniel
Pritchard for believing in me and encouraging me to write the book. I also would like to thank the members
of my Silicon Valley Ruby meetup, who provided valuable feedback about the early material in this book at
the bootcamps and tutorials. Thanks to Emily Bache for providing me with very candid technical feedback,
and Randy Coulman for his inspiring presentations and technical review of one of the chapters. I would also
like to thank Mayank Suri for challenging me and pushing me out of my comfort zone in order to accomplish
bigger goals in my career.
This book builds on top of the work of others like Kent Beck, Robert Martin, Eric Evans, Gerard
Meszaros, Michael Feathers, and others mentioned in the book. I cannot thank Ryan Davis enough for
building a simple and elegant testing framework with a gentle learning curve for beginners.
This book would not have been a reality without Steve Anglin, Mark Powers, and Matthew Moodie. I am
deeply indebted to the Apress team for recognizing my talent and providing me with a channel for my voice.
Last but not least, thanks to Ronald Petty for patiently reviewing my book and pointing out the mistakes.
This book is the result of my search for solutions to overcome the difficulties I faced when I started to
learn TDD. It also distills the design knowledge I have acquired over my career. I sincerely hope that this
book shows empathy for beginners and makes it easier for them to learn TDD.

xix
Introduction

Experience is simply the name we give our mistakes.


—Oscar Wilde

This book is the result of my struggle to learn Test Driven Development. I started documenting the
difficulties that I faced and what I did to overcome them. I started sharing my tips with the members of
my Silicon Valley Ruby meetup and on my blog. You will learn both from my mistakes and from other
developers in this book.

Mistakes are the portals of discovery.


—James Joyce

More importantly, if you document your mistakes and start analyzing them, you too will discover new tips
that you can share with others. Mastering TDD is a journey. I hope you enjoy the journey as much as I have
enjoyed writing this book. Good luck.

xxi
CHAPTER 1

The Basics

This chapter will discuss coding kata, basic terminology, overcoming difficulty in TDD, and how to improve
your TDD skills over time. We will look at the distinction between intent and implementation and its role in
coming up with elegant solutions. We will briefly discuss the basics of Test Driven Development (TDD) and
how problem-solving skills fit into TDD. We will also cover designing test cases, assertion, Canonical Test
Structure, and how to avoid common mistakes.

Terminology
This section will introduce you to the basic terminology required to grasp the material in this book. We will
look at basic terms such as kata, coding kata, domain, problem domain, and solution domain.

Kata
Kata is a Japanese word meaning form. In martial arts, it describes a choreographed pattern of movements
used to train yourself to the level of muscle memory. The focus is on making small improvements during
practice. Figure 1-1 shows a choreographed pattern of movements in martial arts.

Figure 1-1. A choreographed pattern of movements

© Bala Paranj 2017 1


B. Paranj, Test Driven Development in Ruby, DOI 10.1007/978-1-4842-2638-4_1
Chapter 1 ■ The Basics

Coding Kata
A coding kata is a short exercise that is thirty minutes to an hour long. It can be coded in many different
ways. It is likely that coding katas have many solutions. The focus is on learning when you work through
them. The goal is to practice in order to improve your skills, not to achieve perfection.

Domain
What comes to mind when you hear terms such as equity, debt, gross margin, and net income? How about
contour, contrast, opacity, and form? Here’s another example: parallel, ordinate, arc, and angle. A domain is
defined as a specific sphere of activity or knowledge. The first example corresponds to finance. The second
example corresponds to visual communication, and the third corresponds to geometry. Figure 1-2 shows
three different domains—finance, visual communication, and math—consisting of abstractions found in
those domains.

Figure 1-2. Examples of domains

Problem Domain
The problem domain refers to real-world things and concepts related to a problem.

Solution Domain
The solution domain refers to real-world things and concepts related to a solution.

Domain Expert
A domain expert is someone with special knowledge or skill in a particular domain. For instance, an
accountant is an expert in the accounting domain. The development of accounting software requires
knowledge in two different domains, namely accounting and software.

2
Chapter 1 ■ The Basics

Domain Knowledge
Domain knowledge is expertise in a particular problem domain. It is a critical ingredient in coming up with
abstractions that create elegant solutions.

Defining the Problem Domain and the Solution Domain


When you read a problem statement in a textual form, you will find concepts in the problem statement.
You can list the concepts you find and group them to come up with the problem domain name. Figure 1-3
illustrates the process of coming up with the problem domain name from a given problem statement.

Figure 1-3. Process of finding the domain name

Let’s now see an example of problem domain and solution domain. Let’s say you have leaking sink
problem in your kitchen. You search on the Internet for the term leaking sink. The phrase leaking sink is
found in the problem domain. Once you read about the solution to this problem, you learn about things
like: clevis screw, stopper rod, clevis, retaining nut and so on. These terms belong to the solution domain.
You watch a video and find out that you need to buy a retaining nut to fix the leak. You now start using this
term found in the solution domain, retaining nut, to find the nearest store carrying this item. So, the term:
retaining nut belongs to the solution domain.

Learning TDD
Learning by Coding Kata
Why coding Kata? Test Driven Development (TDD) is a difficult but learnable skill. So, in order to answer
this question, we need to look at why TDD is difficult.

TDD is not a testing technique. It’s an analysis technique, a design technique, really a
technique for all activities of development.
—Kent Beck, Test Driven Development by Example

3
Chapter 1 ■ The Basics

By using the small but precise nature of the coding kata to practice these skills separately, you can
move past this difficulty and hone your TDD skills. So, coding kata is the best way to learn TDD. How do you
practice a coding kata? You will work through a coding kata by following the five steps of TDD, which will be
discussed in an upcoming section.

Learning Retrospective
After you complete a coding kata using TDD, reflect on the TDD practice session. Ask yourself the following
questions:
• What went well during the TDD session?
• What went wrong during the TDD session?
• What can I do differently next time to improve?

The answers to these questions will tell you where you need to focus your efforts in your next practice
session so as to improve your skills. It’s a good idea to keep a journal that records the coding kata name and
the answers to these questions for each practice session.

Intent vs. Implementation


In this section, we will discuss the intent and implementation, or the specification and implementation.
We will look at examples to illustrate the differences between intent and implementation, why we need to
separate them, and how to separate them in the code.

Intent
The dictionary definition of intent is determined to do something. If you want to travel in your car, your intent
is to drive your car. You don’t reach into the transmission and pull levers to drive. You can drive without
knowing the details of the car engine. You use the visible parts of the car, such as the steering wheel, gas
pedal, brake, and gears, to drive. You can express your intent by using the public interface of the car. In
programming terms, the intent-revealing drive() method is used. The public interface would consist of
things you can do to a car, such as start, stop, drive, turn, and so on.

Implementation
The things under the hood of the car make up the implementation. Only your car mechanic knows about the
details of the car engine. You may be aware of the 3.0 liter V-6 engine, but you have no idea of how it works.
There could be methods that are internal to the class, such as burn_fuel(), that are not part of the public
interface of the car. This means the user does not directly invoke any private methods of the car.

Intent and Implementation


We will now see three examples of intent and implementation, the difference between them, and why we
need to separate them.

4
Chapter 1 ■ The Basics

Music
Music is composed by music composers. Music composers organize and develop the music to create a
written score that can be interpreted by performers. Performers play the music using different musical
instruments by referring the sheet music. Sheet music is not music. Sheet music is a visual abstraction of
music. To be specific, it is a symbolic abstraction of music that can be read by anyone who knows how to
read music notation. The composers communicate with other musicians across space and time using music
notation. This is the intent, the what, the logical design. Figure 1-4 shows sheet music that communicates
with other musicians.

Figure 1-4. Sheet music is a symbolic abstraction of music

Playing the music with a musical instrument is the implementation, the how, or the physical design.
There are many physical designs for a given logical design. In this example, the same sheet music can be
used to play the music using different musical instruments. Figure 1-5 shows music being performed by a
musical instrument, achieved by interpreting the sheet music.

5
Chapter 1 ■ The Basics

Figure 1-5. Music is played using a musical instrument

Lyrics
A lyricist writes the words for a song by organizing sections into one of the agreed upon structures. This
provides the roadmap for the song. Let’s consider the lyrics for the song “Come Together.” John Lennon
wrote this song. This is the what. The how in this case are the performances by The Beatles, Aerosmith, and
Michael Jackson of the same song, “Come Together.”

Home Plan
An architect gets requirements from the client. A hand-drawn sketch consisting of bubbles, squares,
and rectangles captures the idea of where things are and how they interrelate. This diagram becomes
architecture. Figure 1-6 shows the blueprint of a house that captures the design decisions made by the
architect. This blueprint of a house is the what. It is a visual abstraction of the design. You can build many
houses using the same blueprint.

6
Chapter 1 ■ The Basics

Figure 1-6. Blueprint of a house

Table 1-1 summarizes the intent and implementation of some common, everyday things that you
encounter.

Table 1-1. Intent vs. Implementation

Intent Implementation
Drive a car Internal mechanism of a car that drives
Represent music The process of playing music with a musical instrument
Lyrics of a song The unique way of singing a song by a singer
Plan of a home Houses that conform to the same blueprint but look different

Separate Intent from Implementation


We need to separate the intent from implementation. Why? Because it allows us to change the
implementation without breaking the tests. The intent is the focus of the tests. The implementation is the
focus of the production code. As long as the behavior is the same, the implementation changes should not
break the tests.

7
Chapter 1 ■ The Basics

Sheep Example
So, how do we separate the intent from implementation? We can use Chris Stevenson’s TestDox (https://
en.wikipedia.org/wiki/TestDox). TestDox expresses the subject in the code as part of a sentence. Here is
an example:
• A sheep eats grass.
• A sheep bleats when frightened.
• A sheep produces delicious milk.
• A sheep moves away from sheep dogs.
In this example, the sheep is the subject. Its behavior is expressed in a sentence. This can be
automatically converted to specifications in code. Figure 1-7 shows the behavior of a sheep expressed as
specifications in code.

Figure 1-7. Specifications in ĉode

In this example, we are using the spec style of the Minitest testing framework to describe the behavior of
a sheep. Minitest ships with the Ruby language. When you think about a system from the outside, you focus
on the intent. In this case, what does the sheep do?

Test API Example


For a realistic example, examine Figure 1-8 from the RSpec documentation that shows developers how the
eq() method in RSpec (http://rspec.info) works.

8
Chapter 1 ■ The Basics

Figure 1-8. Specification that shows RSpec API usage example

The example is easy to read and shows how the eq() method can be used to compare two strings that
are equal and not equal. (Source: https://www.relishapp.com/rspec/rspec-expectations/docs/built-
in-matchers/equality-matchers)

Bowling Game Example


Let’s look at an example that uses a bowling game scoring program to illustrate how to discover an
intent-revealing interface.

it 'score is 10 for a strike - knocking down all ten pins' do


  game = BowlingGame.new
  10.times { game.roll(1) }

  assert_equal 10, game.score


end

9
Chapter 1 ■ The Basics

This test does not reveal the intent of rolling ten times. We don’t know why it invokes the roll method
ten times, because the intent is hidden. We can make the intent explicit by asking the question: “What does
it mean to hit all ten pins?” In the bowling game domain, it means a strike. So, we can express it directly in
code as follows:

it 'score is 10 for a strike - knocking down all ten pins' do


  game = BowlingGame.new
  game.strike

  assert_equal 10, game.score


end

The strike method is intent-revealing and expresses the domain concept mentioned in the test name
directly in the code. It clearly communicates the meaning of a strike in a bowling game to other developers.

Precision in Language and Meaning


An infant cries, and you don’t know whether it is hungry or has tummy trouble. If you give it milk, it stops
crying. As it grows, the request “Milk!” becomes “Me Milk!” and later “Please give me some milk to drink.”
Children learn as they grow and their language acquires more precise meaning. Similarly, as the software
grows, the tests acquire more precise meaning.
A proposition in logic is a statement that expresses a concept that can be either true or false. For
instance, we can make valid propositions about the concept of grass, as follows:
• Grass is green.
• Grass is a plant.
• Grass grows.
• Grass is a monocot.
And so on, leading to increased meaning and precision of meaning for the concept of grass. We can
express this as specifications in code similar to the sheep example, as shown in Figure 1-9.

Figure 1-9. Specifications for grass

Now, consider the following:


• It has a wide opening to the water tank.
• It has a marked tank for exact water filling.
• It has two-hour auto-shutoff.

10
Chapter 1 ■ The Basics

• It has a filter basket.


• It has a thermal carafe.
• It is usually in the kitchen.
• It has a sink.
• It maintains the temperature of the drink inside.
What is it? At some point in the sequence, you connected with the pattern and understood it was a
description of a coffee maker. From that point, each statement confirmed your understanding. We can
express these statements as specifications in code that describes the coffee maker. We will discuss this in
more detail in an upcoming section on designing the sequence of test cases.

Tests Are Executable Documentation


Let’s say you installed a gem and need to figure out how to use it. You should be able to look at the tests and
see examples that show you how to use the library. It will answer questions such as:
• Which class should I instantiate?
• How do I instantiate the class?
• Which method should I invoke?
• What parameters does the method need?
And so on. However, you should not read the source code of the gem to figure out the answers to these
questions. The developer of the gem has achieved the desired separation of intent and implementation only
when one can write programs that use that gem by referring only to the tests that come with the gem. Tests
are executable documentation and always tell the truth. Other forms of documentation, such as wiki, source
code commenting, and so on, can get out of sync with the production code.
The tests are a way for the library developer to communicate with other developers about the library.
Tests must be readable and easy to understand for someone who is new to the library.

Shift in Mental State


You focus on specifying what a system should do when you are reading the problem description. This is
analysis. The mental state is the what during this activity. You will be looking at the problem domain. For
what, you must focus on the input and output of the system, as illustrated in Figure 1-10. You will focus on
what is visible outside of a system and ignore what is inside the system. You will ignore the details and treat
the system under test as a black box.

Figure 1-10. Mental focus is on what

11
Chapter 1 ■ The Basics

From what, we move to how. The focus shifts from analysis to design. You will be looking at the solution
domain. Your mental state is how. For how, you will focus on what is inside the system, as illustrated in
Figure 1-11. You will consider the details of the system under test.

Figure 1-11. Mental focus is on how

A professional artist starts to draw a portrait with a general outline that gives the basic shape of the face,
eyes, and so on. At this stage, the attributes of a person, such as eyes and lips, could be those of anyone. They
don’t look unique to the portrait subject. As the artist gradually adds more details and adds depth using
shading, the drawing comes to life and resembles the subject. The final portrait fits the structure provided by
the general outline drawn in the initial stages of the drawing. Software developers work in a similar way in
order to write software to solve a given problem.

Overview of TDD
This section is a brief introduction to Test Driven Development. We will answer questions such as what,
why, and how. We will discuss why we start with a failing test and are minimal when implementing the
production code. We will also see how TDD separates the intent from implementation, how to get all the
benefits of TDD, and, finally, what makes TDD difficult.

Test Driven Development


Test Driven Development is a software development practice where the test is written before the production
code. The goal is clean code that works. It leads to better quality and fewer defects in code. It eliminates the
need to spend days in a debugger to hunt down hard-to-find bugs. Thus, it reduces debugging efforts. Why
have clean code that works as the goal?

Clean code that works gives you a chance to learn all the lessons that the code has to teach
you. If you only slap together the first thing you think of, you never have time to think of a
second, better thing. The intent is to learn and come up with a better solution.
—Kent Beck, Test Driven Development by Example

12
Chapter 1 ■ The Basics

The Five Steps of TDD


Kent Beck is the creator of extreme programming, a software development methodology that avoids rigid
formal specifications for a collaborative and iterative design process. Kent Beck sums up the fives steps of
TDD as follows:
1. Quickly add a test.
2. Run all tests and see the new one fail. Since there is no code yet to make the test
pass, this test will fail.
3. Make a little change to pass the test as quickly as possible.
4. Run all tests and see them all succeed.
5. Refactor to remove duplication.
Figure 1-12 shows how the red-green-refactor steps repeat to form the TDD cycle.

Figure 1-12. The TDD steps repeat to form the TDD cycle

In the first step, we write a test. In the second step, we record a requirement as a test. We also explicitly
design the client API. Designing the API here means answering questions such as the following:
• Does the method name reveal the intent?
• Should this be an instance method or a class method?
• What are the parameters to this method?
• What are the required parameters?
• What are the optional parameters?
• Should this parameter be passed in to the constructor instead of being passed in to
the method?
• Should the parameter have a default value?

13
Another Random Scribd Document
with Unrelated Content
That each thrice third night from its rim there fell
Eight rings, as their parent fair.”
The Dwarfs, Oehlenschläger (Pigott’s tr.).

Now a lump of iron was cast in the flames, and with a new caution
not to forfeit their success by inattention, Sindri passed out, leaving
Brock to ply the bellows and wrestle with the gadfly, which this time
stung him above the eye until the blood began to flow in such a
stream, that it prevented his seeing what he was doing. Hastily raising
his hand for a second, Brock dashed aside the stream of blood; but
short as was the interruption, Sindri uttered an exclamation of
disappointment when he drew his work out of the fire, for the hammer
he had fashioned had too short a handle.

“Then the dwarf raised his hand to his brow for the smart,
Ere the iron well out was beat,
And they found that the haft by an inch was too short,
But to alter it then ’twas too late.”
The Dwarfs, Oehlenschläger (Pigott’s tr.).

Notwithstanding this mishap, Brock was so sure of winning the


wager that he did not hesitate to present himself before the gods in
Asgard, gave Odin the ring Draupnir, Frey the boar Gullin-bursti, and
Thor the hammer Miölnir, whose power none could resist.
Loki immediately gave the spear Gungnir to Odin, the ship
Skidbladnir to Frey, and the golden hair to Thor; but although the latter
immediately grew upon Sif’s head and was unanimously declared
more beautiful than her own locks had ever been, the gods decreed
that Brock had won the wager, for the hammer Miölnir, in Thor’s
hands, would prove invaluable against the frost giants on the last day.

“And at their head came Thor,


Shouldering his hammer, which the giants know.”
Balder Dead (Matthew Arnold).
Wishing to save his head, Loki fled, but was soon overtaken by
Thor, who brought him back and handed him over to Brock, telling
him, however, that although Loki’s head was rightfully his, he must not
touch his neck. Thus hindered from obtaining full vengeance, the
dwarf tried to sew Loki’s lips together, but, as his sword would not
pierce them, he was obliged to borrow his brother’s awl. However,
Loki, after enduring the gods’ gibes in silence for a little while,
managed to cut the string and was soon as loquacious as ever.
THOR.
In spite of his redoubtable hammer, Thor was never considered as
the injurious god of the storm, who destroyed peaceful homesteads
and ruined the harvest by sudden hail storms and cloud bursts, for the
Northerners fancied he hurled it only against ice giants and rocky
walls, reducing the latter to powder to fertilize the earth and make it
yield plentiful fruit to the tillers of the soil.
In Germany, where the eastern storms are always cold and
blighting, while the western bring warm rains and mild weather, Thor
was supposed to journey always from west to east, to wage war
against the evil spirits which would fain have enveloped the country in
impenetrable veils of mist and have bound it in icy fetters.
As the giants from Jötun-heim were continually sending out cold
Journey to blasts of wind to nip the tender buds and hinder the
Jötun-heim. growth of the flowers, Thor once made up his mind to
go and force them to better behavior. Accompanied by
Loki he therefore set out in his chariot. After riding for a whole day the
gods came at nightfall to the confines of the giant-world, where,
seeing a peasant’s hut, they resolved to spend the night and refresh
themselves.
Their host was hospitable but very poor, and Thor seeing that he
would scarcely be able to supply the necessary food to satisfy his by
no means small appetite, slew both his goats, which he cooked and
began to eat, inviting his host and family to partake freely of the food
thus provided, but cautioning them to throw all the bones, without
breaking them, into the skins spread out on the floor.
The peasant and his family ate heartily, but a youth called Thialfi,
encouraged by Loki, ventured to break one of the bones and suck out
the marrow, thinking his disobedience would never be detected. On
the morrow, however, Thor, ready to depart, struck the goat skins with
his hammer Miölnir, and immediately the goats sprang up as lively as
before, except that one seemed somewhat lame. Perceiving in a
second that his commands had been disregarded, Thor would have
slain the whole family in his wrath. The culprit acknowledged his fault,
however, and the peasant offered to compensate for the loss by giving
the irate god not only his son Thialfi, but also his daughter Roskva, to
serve him forever.
Charging the man to take good care of the goats, which he left
there until he should return, and bidding the young peasants
accompany him, Thor now set out on foot with Loki, and after walking
all day found himself at nightfall in a bleak and barren country, which
was enveloped in an almost impenetrable gray mist. After seeking for
some time, Thor saw through the fog the uncertain outline of what
looked like a peculiar-shaped house. Its open portal was so wide and
high that it seemed to take up all one side of the house. Entering and
finding neither fire nor light, Thor and his companions flung
themselves wearily down on the floor to sleep, but were soon
disturbed by a peculiar noise, and a prolonged trembling of the ground
beneath them. Fearing lest the main roof should fall during this
earthquake, Thor and his companions took refuge in a wing of the
building, where they soon fell sound asleep. At dawn, the god and his
companions passed out, but they had not gone very far ere they saw
the recumbent form of a sleeping giant, and perceived that the
peculiar sounds which had disturbed their rest were produced by his
snores. At that moment the giant awoke, arose, stretched himself,
looked about him for his missing property, and a second later he
picked up the object which Thor and his companions had mistaken in
the darkness for a house. They then perceived with amazement that
the wing in which they had all slept was the separate place in a mitten
for the giant’s great thumb! Learning that Thor and his companions
were on their way to Utgard, as the giants’ realm was also called,
Skrymir, the giant, proposed to be their guide; and after walking with
them all day, he offered them the provisions in his wallet ere he
dropped asleep. But, in spite of strenuous efforts, neither Thor nor his
companions could unfasten the knots which Skrymir had tied.

“Skrymir’s thongs
Seemed to thee hard,
When at the food thou couldst not get,
When, in full health, of hunger dying.”
Sæmund’s Edda (Thorpe’s tr.).

Angry because of his snoring, which kept them awake, Thor thrice
dealt him fearful blows with his hammer. These strokes, instead of
Utgard-loki. annihilating the monster, merely evoked sleepy
comments to the effect that a leaf, a bit of bark, or a
twig from a bird’s nest overhead had fallen upon his face. Early on the
morrow, Skrymir left Thor and his companions, pointing out the
shortest road to Utgard-loki’s castle, which was built of great ice
blocks, with huge glittering icicles as pillars. The gods, slipping
between the bars of the great gate, presented themselves boldly
before the king of the giants, Utgard-loki, who, recognizing them,
immediately pretended to be greatly surprised at their small size, and
expressed a wish to see for himself what they could do, as he had
often heard their prowess vaunted.
Loki, who had fasted longer than he wished, immediately declared
he was ready to eat for a wager with any one. So the king ordered a
great wooden trough full of meat to be brought into the hall, and
placing Loki at one end and his cook Logi at the other, he bade them
see which would win. Although Loki did wonders, and soon reached
the middle of the trough, he still found himself beaten, for whereas he
had picked the bones clean, his opponent had devoured both them
and the trough.
Smiling contemptuously, Utgard-loki said that it was evident they
could not do much in the eating line, and so nettled Thor thereby, that
he declared if Loki could not eat more than the voracious cook, he felt
confident he could drain the biggest vessel in the house, such was his
unquenchable thirst. Immediately a horn was brought in, and, Utgard-
loki declaring that good drinkers emptied it at one draught, moderately
thirsty persons at two, and small drinkers at three, Thor applied his
lips to the rim. But, although he drank so deep that he thought he
would burst, the liquid still came almost up to the rim when he raised
his head. A second and third attempt to empty this horn proved
equally unsuccessful. Thialfi then offered to run a race, and a young
fellow named Hugi soon outstripped him, although he made
remarkably good time.
Thor next proposed to show his strength by lifting great weights,
but when challenged to pick up the giant’s cat, he tugged and
strained, only to succeed in raising one paw from the floor, although
he had taken the precaution to enhance his strength as much as
possible by tightening his belt Megin-giörd.

“Strong is great Thor, no doubt, when Megingarder


He braces tightly o’er his rock-firm loins.”
Viking Tales of the North (R. B. Anderson).

An attempt on his part to wrestle with Utgard-loki’s old nurse Elli,


the only opponent deemed worthy of such a puny fellow, ended
equally disastrously, and the gods, acknowledging they were beaten,
were hospitably entertained. On the morrow they were escorted to the
confines of Utgard, where the giant politely informed them that he
hoped they would never call upon him again, as he had been forced to
employ magic against them. He then went on to explain that he was
the giant Skrymir, and that had he not taken the precaution to
interpose a mountain between his head and Thor’s blows, he would
have been slain, as deep clefts in the mountain side testified to the
god’s strength. Next he informed them that Loki’s opponent was Logi
(wild fire); that Thialfi had run a race with Hugi (thought), than which
no swifter runner exists; that Thor’s drinking horn was connected with
the ocean, where his deep draughts had produced a perceptible ebb;
that the cat was in reality the terrible Midgard snake encircling the
world, which Thor had nearly pulled out of the sea; and that Elli, his
nurse, was old age, whom none can resist. Having finished these
explanations and cautioned them never to return or he would defend
himself by similar delusions, Utgard-loki vanished, and although Thor
angrily brandished his hammer to destroy his castle, such a mist
enveloped it that it could not be seen, and the thunder god was
obliged to return to Thrud-vang without having accomplished his
purpose, the extermination of the race of giants.

“The strong-armed Thor


Full oft against giant Jötun-heim did wend,
But spite his belt celestial, spite his gauntlets,
Utgard-Loki still his throne retains;
Evil, itself a force, to force yields never.”
Viking Tales of the North (R. B. Anderson).

As Odin was once dashing through the air on his eight-footed


steed Sleipnir, he attracted the attention of the giant
Thor and
Hrungnir. Hrungnir, who proposed a race, declaring he was sure
his own steed Gullfaxi could rival Sleipnir in speed. In
the heat of the race, Hrungnir did not even notice in what direction
they were going, and, in the vain hope of overtaking Odin, urged his
steed on to the very gates of Valhalla. Discovering where he was, the
giant then grew pale with fear, for he knew he had jeopardized his life
by venturing into the stronghold of the gods, his hereditary foes.
The Æsir, however, were too honorable to take even an enemy at
such a disadvantage, and, instead of doing him any harm, asked him
into their banqueting halls, where he proceeded to indulge in liberal
potations of the heavenly mead set before him. He soon grew so
excited that he began to boast of his power, declaring he would come
some day and take possession of Asgard, which he would destroy, as
well as all the gods, excepting only Freya and Sif, upon whom he
gazed with an admiring, drunken leer.
The gods, knowing he was not responsible, let him talk
unmolested; but Thor, coming home just then from one of his
journeys, and hearing him propose to carry away his beloved Sif, flew
into a terrible rage. He furiously brandished his hammer, intending to
annihilate the boaster. This the gods would not permit, however, and
they quickly threw themselves between the irate Thunderer and their
guest, imploring the former to respect the sacred rights of hospitality,
and not desecrate their peace-stead by shedding blood.
Thor at last consented to bridle his wrath, providing the giant
Hrungnir would appoint a time and place for a holmgang, as a
Northern duel was generally called. Thus challenged, Hrungnir
promised to meet Thor at Griottunagard, the confines of his realm,
three days later, and departed somewhat sobered by the fright he had
experienced. When his fellow giants heard how rash he had been,
they chided him sorely; but hearing he was to have the privilege of
being accompanied by a squire, whom Thialfi would engage in fight,
they proceeded to construct a creature of clay, nine miles long, and
proportionately wide, whom they called Mokerkialfi (mist wader). As
they could find no human heart big enough to put in this monster’s
breast, they secured that of a mare, which, however, kept fluttering
and quivering with apprehension. The day of the duel arrived.
Hrungnir and his squire were on the ground awaiting the arrival of
their respective opponents. The giant had not only a flint heart and
skull, but also a shield and club of the same substance, and therefore
deemed himself well-nigh invincible. But when he heard a terrible
noise, and Thialfi came running up to announce his master’s coming,
he gladly followed the herald’s advice and stood upon his shield, lest
the thunder god should come up from the ground and attack him
unprotected.
A moment later, however, he saw his mistake, for, while Thialfi
attacked Mokerkialfi with a spade, Thor came rushing up and flung his
hammer full at his opponent’s head. Hrungnir, to ward off the blow,
interposed his stone club, which was shivered into pieces, that flew all
over the earth, supplying all the flint stones to be found, and one
fragment sank deep in Thor’s forehead. As the god dropped fainting to
the ground, his hammer crashed against the head of Hrungnir, who
fell down dead beside him, in such a position that one of his
ponderous legs was thrown over the recumbent god.

“Thou now remindest me


How I with Hrungnir fought,
That stout-hearted Jötun,
Whose head was all of stone;
Yet I made him fall
And sink before me.”
Sæmund’s Edda (Thorpe’s tr.).

Thialfi, who, in the mean while, had disposed of the great clay
giant with its cowardly mare’s heart, now rushed to his master’s
rescue; but all his efforts and those of the assembled gods, whom he
quickly summoned, could not raise the pinioning leg. While they were
standing there, helplessly wondering what they should do next, Thor’s
little son Magni came up. According to varying accounts, he was then
only three days or three years old, but he quickly seized the giant’s
foot, and, unaided, set his father free, declaring that had he only been
summoned sooner he would easily have disposed of both giant and
squire. This exhibition of strength upon his part made the gods
wonder greatly, and helped them to recognize the truth of the various
predictions, which one and all declared that their descendants would
be mightier than they, would survive them, and would rule in their turn
over the new heaven and earth.
To reward his son for his timely aid, Thor gave him the steed
Gullfaxi (golden-maned), to which he had fallen heir by right of
conquest, and Magni ever after rode this marvelous horse, which
almost equaled the renowned Sleipnir in speed and endurance.
After vainly trying to remove the stone splinter from his forehead,
Thor sadly returned home to Thrud-vang, where Sif’s
Groa, the
sorceress. loving efforts were equally unsuccessful. She therefore
resolved to send for Groa (green-making), a sorceress,
noted for her skill in medicine and for the efficacy of her spells and
incantations. Groa immediately signified her readiness to render every
service in her power to the god who had so often benefited her, and
solemnly began to recite powerful runes, under whose influence Thor
felt the stone grow looser and looser. In his delight at the prospect of a
speedy deliverance, Thor wished to reward the enchantress. Knowing
that nothing could give greater pleasure to a mother than the prospect
of seeing a long-lost child, he therefore told her he had recently
crossed the Elivagar, or ice streams, to rescue her little son Orvandil
(germ) from the frost giants’ cruel power, and had succeeded in
carrying him off in a basket. But, as the little rogue would persist in
sticking one of his bare toes through a hole in the basket, it had been
frost bitten, and Thor, accidentally breaking it off, had flung it up into
the sky, where it shone as a star, known in the North as “Orvandil’s
Toe.”
Delighted with these tidings, the prophetess paused in her
incantations to express her joy, but, having forgotten just where she
left off, she was never able to continue her spell, and the flint stone
remained imbedded in Thor’s forehead, whence it could never be
dislodged.
Of course, as Thor’s hammer always did him such good service, it
was the most prized of all his possessions, and his dismay was very
great when he awoke one morning and found it gone. His cry of anger
and disappointment soon brought Loki to his side, and to him Thor
confided the secret of his loss, declaring that were the giants to hear
of it, they would soon attempt to storm Asgard and destroy the gods.

“Wroth waxed Thor, when his sleep was flown,


And he found his trusty hammer gone;
He smote his brow, his beard he shook,
The son of earth ’gan round him look;
And this the first word that he spoke:
‘Now listen what I tell thee, Loke;
Which neither on earth below is known,
Nor in heaven above: my hammer’s gone.’”
Thrym’s Quida (Herbert’s tr.).

Loki declared he would try to discover the thief and recover the
hammer, if Freya would only lend him her falcon
Thor and
Thrym. plumes, and immediately hastened off to Folkvang to
borrow them. In the form of a bird he then winged his
flight across the river Ifing, and over the barren stretches of Jötun-
heim, where he shrewdly suspected the thief was to be found. There
he saw Thrym, prince of the frost giants and god of the destructive
thunder storm, sitting alone on a hillside, and, artfully questioning him,
soon learned that he had stolen the hammer, had buried it deep
underground, and would never give it up unless Freya were brought to
him, in bridal array, ready to become his wife.

“I have the Thunderer’s hammer bound


Fathoms eight beneath the ground;
With it shall no one homeward tread
Till he bring me Freya to share my bed.”
Thrym’s Quida (Herbert’s tr.).
Indignant at the giant’s presumption, Loki returned to Thrud-vang,
where Thor, hearing what he had learned, declared it would be well to
visit Freya and try to prevail upon her to sacrifice herself for the
general good. But when the Æsir told the goddess of beauty what they
wished her to do, she flew into such a passion that even her necklace
burst. She told them that she would never leave her beloved husband
for any god, and much less to marry an ugly old giant and dwell in
Jötun-heim, where all was dreary in the extreme, and where she
would soon die of longing for the green fields and flowery meadows, in
which she loved to roam. Seeing that further persuasions would be
useless, Loki and Thor returned home and there devised another plan
for recovering the hammer. By Heimdall’s advice, Thor borrowed and
reluctantly put on all Freya’s clothes and her necklace, and enveloped
himself in a thick veil. Loki, having attired himself as a handmaiden,
then mounted with him in the goat-drawn chariot, to ride to Jötun-
heim, where they intended to play the respective parts of the goddess
of beauty and of her attendant.

“Home were driven


Then the goats,
And hitched to the car;
Hasten they must—
The mountains crashed,
The earth stood in flames:
Odin’s son
Rode to Jötun-heim.”
Norse Mythology (R. B. Anderson).

Thrym welcomed his guests at the palace door, overjoyed at the


thought that he was about to secure undisputed possession of the
goddess of beauty, for whom he had long sighed in vain. He quickly
led them to the banquet hall, where Thor, the bride elect, almost
disgraced himself by eating an ox, eight huge salmon, and all the
cakes and sweets provided for the women, washing down these
miscellaneous viands with two whole barrels of mead.
The giant bridegroom watched these gastronomic feats with
amazement, and was not even reassured when Loki confidentially
whispered to him that the bride was so deeply in love with him that
she had not been able to taste a morsel of food for more than eight
days. Thrym then sought to kiss the bride, but drew back appalled at
the fire of her glance, which Loki explained as a burning glance of
love. The giant’s sister, claiming the usual gifts, was not even noticed;
so Loki again whispered to the wondering Thrym that love made
people absent-minded. Intoxicated with passion and mead, which he,
too, had drunk in liberal quantities, the bridegroom now bade his
servants produce the sacred hammer to consecrate the marriage, and
as soon as it was brought he himself laid it in the pretended Freya’s
lap. The next moment a powerful hand closed over the short handle,
and the weapon, rapidly hurled by Thor, soon slew the giant, his sister,
and all the invited guests.

“‘Bear in the hammer to plight the maid;


Upon her lap the bruiser lay,
And firmly plight our hands and fay.’
The Thunderer’s soul smiled in his breast;
When the hammer hard on his lap was placed,
Thrym first, the king of the Thursi, he slew,
And slaughtered all the giant crew.”
Thrym’s Quida (Herbert’s tr.).

Leaving a smoking heap of ruins behind them, the gods then


drove rapidly back to Asgard, where the borrowed garments were
given back to Freya, and the Æsir all rejoiced at the recovery of the
precious hammer. When next Odin glanced towards that part of Jötun-
heim from the top of his throne Hlidskialf, he saw the ruins covered
with tender green shoots, for Thor, having conquered his enemy, had
taken possession of his land, which no longer remained barren and
desolate as before, but brought forth fruit in abundance.
Loki, in search of adventures, once borrowed Freya’s falcon garb
Thor and and flew off to another part of Jötun-heim, where he
Geirrod. perched on top of the gables of Geirrod’s house, and,
gazing about him, soon attracted the attention of this giant, who bade
one of his servants catch the bird. Amused at the fellow’s clumsy
attempts to secure him, Loki flitted about from place to place, only
moving just as the giant was about to lay hands upon him, until,
miscalculating his distance, he suddenly found himself a captive.
Geirrod, gazing upon the bird’s bright eyes, shrewdly suspected
that it was a god in disguise, and to force him to speak, locked him up
in a cage, where he kept him for three whole months without food or
drink. Conquered at last by hunger and thirst, Loki revealed his
identity, and obtained his release by promising that he would induce
Thor to visit Geirrod without his hammer, pelt, or magic gauntlet. Loki
then flew back to Asgard, and told Thor that he had been royally
entertained, and that his host had expressed a strong desire to see
the powerful thunder-god, of whom Loki had told him such wonderful
tales. Flattered by this artful speech, Thor was soon brought to
consent to a journey to Jötun-heim, and immediately set out, leaving
his three marvelous weapons at home. He and Loki had not gone very
far, however, ere they came to the house of the giantess Grid, one of
Odin’s many wives, who, seeing Thor disarmed, lent him her own
girdle, staff, and glove, warning him to beware of treachery. Some
time after leaving her, Thor and Loki came to the river Veimer, which
the thunder-god, accustomed to wading, coolly prepared to ford,
bidding Loki and Thialfi cling fast to his belt if they would come safe
across.
In the middle of the stream, however, a sudden cloudburst and
freshet overtook them; the waters began to rise and roar, and
although Thor leaned heavily upon his staff, he was almost swept
away by the force of the raging current.

“Wax not, Veimer,


Since to wade I desire
To the realm of the giants!
Know, if thou waxest,
Then waxes my asamight
As high as the heavens.”
Norse Mythology (R. B. Anderson).
Looking up the stream, Thor now became aware of the presence
of Geirrod’s daughter Gialp, and rightly suspected that she was the
cause of the storm. He picked up a huge bowlder, which he flung at
her, muttering that the best place to dam a river was at its source. The
rock had the desired effect, for the giantess fled, the waters abated,
and Thor, exhausted but safe, pulled himself up on the opposite bank
by a little shrub, the mountain-ash or sorb, which has since been
known as “Thor’s salvation,” and considered gifted with occult powers.
After resting awhile the god resumed his journey; but upon arriving at
Geirrod’s house he was so exhausted that he sank wearily down upon
the only chair in sight. To his surprise, however, he felt it rise beneath
him, and fearing lest he should be crushed against the rafters, he
braced the borrowed staff against the ceiling and forced the chair
downward with all his might. A terrible cracking, sudden cries, and
moans of pain proved that he had broken the backs of the giant’s
daughters, Gialp and Greip, who had slipped under his chair and had
treacherously tried to slay him.

“Once I employed
My asamight
In the realm of giants,
When Gialp and Greip,
Geirrod’s daughters,
Wanted to lift me to heaven.”
Norse Mythology (R. B. Anderson).

Geirrod now challenged Thor to show his strength and skill, and
without waiting for the preconcerted signal, flung a red-hot wedge at
him. Thor, quick of eye and a practiced catcher, caught the missile
with the giantess’s iron glove, and hurled it back at his opponent.
Such was the force of the god, that the missile passed, not only
through the pillar behind which the giant had taken refuge, but through
him and the wall of the house, and buried itself deep in the earth
without.
Thor then marched up to the giant’s corpse, which at the blow
from his weapon had been changed into stone, and set it up in a
conspicuous place, as a monument of his strength and of the victory
he had won over his redoubtable foes, the mountain giants.
Thor’s name has been given to many of the places he was wont to
Worship of frequent, such as the principal harbor of the Faroe
Thor. Islands, and to families which claim to be descended
from him. It is still extant in such names as Thunderhill
in Surrey, and in the family names of Thorburn and Thorwaldsen, but
is most conspicuous in the name of one of the days of the week,
Thor’s day or Thursday.

“Over the whole earth


Still is it Thor’s day!”
Saga of King Olaf (Longfellow).

Thor was considered a preëminently benevolent deity, and it was


for that reason that he was so widely worshiped and that his temples
arose at Moeri, Hlader, Godey, Gothland, Upsala, and other places,
where the people never failed to invoke him for a favorable year at
Yule-tide, his principal festival. It was customary on this occasion to
burn a great log of oak, his sacred tree, as an emblem of the warmth
and light of summer, which would soon come to drive away the
darkness and cold of winter.
Brides invariably wore red, Thor’s favorite color, which was
considered emblematical of love, and for the same reason betrothal
rings in the North were almost always set with a red stone.
Thor’s temples and statues, like Odin’s, were fashioned of wood,
and the greater number of them were destroyed during the reign of
King Olaf the Saint. According to ancient chronicles, this monarch
forcibly converted his subjects. He was specially incensed against the
inhabitants of a certain province, because they worshiped a rude
image of Thor, which they decked with golden ornaments, and before
which they set food every evening, declaring the god ate it, as no
trace of it was left in the morning.
The people, being called upon in 1030 to renounce this idol in
favor of the true God, promised to consent if the morrow were cloudy;
but when after a whole night spent in ardent prayer, Olaf rapturously
beheld a cloudy day, the obstinate people declared they were not yet
convinced of his God’s power, and would only believe if the sun shone
on the following day.
Once more Olaf spent the night in prayer, but at dawn his chagrin
was great to see the sky overcast. Nevertheless, determined to gain
his end he assembled the people near Thor’s statue, and after
secretly bidding his principal attendant smash the idol with his battle
ax if the people turned their eyes away but for a moment, he began to
address them. Suddenly, while all were listening to him, Olaf pointed
to the horizon, where the sun was slowly breaking its way through the
clouds, and exclaimed, “Behold our God!” While the people one and
all turned to see what he meant, the attendant broke the idol, and a
host of mice and other vermin scattered on all sides. Seeing now that
the statue was hollow, and that the food placed before their god had
been devoured by noxious animals only, the people ceased to revere
Thor, and definitely accepted the faith which King Olaf had so long
and vainly pressed upon them.
CHAPTER V.
TYR.

Tyr, Tiu, or Ziu was the son of Odin, and, according to different
mythologists, his mother was either Frigga, queen of the gods, or a
beautiful giantess whose name is unknown, but who was a
personification of the raging sea. He is the god of martial honor, and
one of the twelve principal deities of Asgard. Although he appears to
have had no special dwelling there, he was always welcome to
Vingolf or Valhalla, and occupied one of the twelve thrones in the
great council hall of Glads-heim.

“The hall Glads-heim, which is built of gold;


Where are in circle ranged twelve golden chairs,
And in the midst one higher, Odin’s throne.”
Balder Dead (Matthew Arnold).

Tyr was regarded also as the god of courage and of war, and
therefore frequently invoked by the various nations of
The god of
war. the North, who cried to him as well as to Odin to
obtain victory. That he ranked next to Odin and Thor is
proved by his name, Tiu, having been given to one of the days of the
week, Tiu’s day, which in modern English has become Tuesday.
Under the name of Ziu, Tyr was the principal divinity of the Suabians,
who originally called their capital, the modern Augsburg, Ziusburg.
This people, venerating the god as they did, were wont to worship
him under the emblem of a sword, his distinctive attribute, and in his
honor held great sword dances, where various figures were carried
out. Sometimes the participants forming two long lines, crossed their
swords, point upwards, and challenged the boldest among their
number to take a flying leap over them. At other times the warriors
joined their sword points closely together in the shape of a rose or
wheel, and when this figure was complete invited their chief to stand
on the navel thus formed of flat, shining steel blades, and then they
bore him upon it through the camp in triumph. The sword point was
further considered so sacred that it became customary to register
oaths upon it.

“... Come hither, gentlemen,


And lay your hands again upon my sword;
Never to speak of this that you have heard,
Swear by my sword.”
Hamlet (Shakespeare).

A distinctive feature of the worship of this god among the Franks


and some other Northern nations was that the priests called Druids
or Godi offered up human sacrifices upon his altars, generally cutting
the bloody or spread eagle upon their victims, that is to say, making
a deep incision on either side of the backbone, turning the ribs thus
loosened inside out, and tearing out the viscera through the opening
thus made. Of course only prisoners of war were treated thus, and it
was considered a point of honor with north European races to
endure this torture without a moan. These sacrifices were made
upon rude stone altars called dolmens, which can still be seen in
Northern Europe. As Tyr was considered the patron god of the
sword, it was deemed indispensable to engrave the sign or rune
representing him upon the blade of every sword—an observance
which the Edda enjoined upon all those who were desirous of
obtaining victory.

“Sig-runes thou must know,


If victory (sigr) thou wilt have,
And on thy sword’s hilt rist them;
Some on the chapes,
Some on the guard,
And twice name the name of Tyr.”
Lay of Sigdrifa (Thorpe’s tr.).

Tyr was identical with the Saxon god Saxnot (from sax, a sword),
and with Er, Heru, or Cheru, the chief divinity of the Cheruski, who
also considered him god of the sun, and deemed his shining sword
blade an emblem of its rays.

“This very sword a ray of light


Snatched from the Sun!”
Valhalla (J. C. Jones).

According to an ancient legend, Cheru’s sword, which had been


fashioned by the dwarfs, sons of Ivald—the same who
Tyr’s sword.
had also made Odin’s spear—was held very sacred
by his people, to whose care he had intrusted it, declaring that those
who possessed it were sure to have the victory over their foes. But
although carefully guarded in the temple, where it was hung so that it
reflected the first beams of the morning sun, it suddenly and
mysteriously disappeared one night. A Vala, druidess, or prophetess,
consulted by the priests, revealed that the Norns had decreed that
whoever wielded it would conquer the world and come to his death
by it; but in spite of all entreaties she refused to tell who had taken it
or where it might be found. Some time after this occurrence a tall
and dignified stranger came to Cologne, where Vitellius, the Roman
prefect, was feasting, called him away from his beloved dainties,
gave him the sword, telling him it would bring him glory and renown,
and hailed him as emperor. This cry was taken up by the assembled
legions, and Vitellius, without making any personal effort to secure
the honor, found himself elected Emperor of Rome.
The new ruler, however, was so absorbed in indulging his taste
for food and drink that he paid but little heed to the divine weapon.
One day while leisurely making his way towards Rome he carelessly
left it hanging in the antechamber to his apartments. A German
soldier seized this opportunity to substitute in its stead his own rusty
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade

Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.

Let us accompany you on the journey of exploring knowledge and


personal growth!

textbookfull.com

You might also like