SlideShare a Scribd company logo
1 of 62
Download to read offline
Chef TDD
(how I learned to stop worrying and love to test.
Wednesday, April 16, 14
• Dan Tracy
• Software Engineer at AWeber Communications
• Primarily a Python developer
• Github - djt5019 <https://github.com/djt5019>
• twitter - @djt5019
Who Am I?
Wednesday, April 16, 14
My name is Dan Tracy and I am a software engineer over at AWeber Communications.
I am primarily a python dev on backend apps. Dev work always in TDD - reject untested pull requests
Became interested in Chef some time ago rougher tools, testing mentality not rooted
Ops had slow, manual, fragile tests
Introduced TDD - Hit some roadbumps
- Highlighted some Infra issues - look at skeletons in our closet
- Otherwise very successful
Why Test?
Wednesday, April 16, 14
Why should we even test in the first place?
What is being gained from testing?
Is it even worth our time?
Hell yes it is.
Wednesday, April 16, 14
When you begin writing tests you eventually develop a distaste for untested code.
Why Test?
• Minimizing risk
Wednesday, April 16, 14
Minimizing risk we throw over the fence when we deploy our changes
Breaking out of the negative feedback loop of being too scared to make changes
Entering a positive feedback loop where we can iterate on our code quickly
Faster to market with new features
Why Test?
• Minimizing risk
• Confidence in what we write
Wednesday, April 16, 14
When we minimize risk we develop confidence in our codebase, if we have confidence in what we write we are inclined to deploy it
faster.
Positive feedback loop when confident
Negative feedback loop when not confident
Why Test?
• Minimizing risk
• Confidence in what we write
• Ensure that we’re pushing out good code
Wednesday, April 16, 14
When we have tests we have a fairweather indicator that our changes didn’t break anything else.
Don’t want this
Wednesday, April 16, 14
This is what your untested code does at 3am.
Requirements for Testing
Wednesday, April 16, 14
Now you’re convinced and ready to write some tests need to know requirements for writing tests
• Tests should be fast!
Test Requirements
Wednesday, April 16, 14
Tests should be fast.
The word fast is relative to the types of tests that we’re running.
There will be more unit tests than integration tests, and more integration tests than acceptance tests.
Negative feedback loop for slow tests
• Tests should be fast!
• Tests should have a narrow scope
Test Requirements
Wednesday, April 16, 14
Tests should have a narrow scope.
Test bare minimum needed to satisfy your requirements.
Your function, LWRP, or code under test should be doing only one thing and doing it well.
• Tests should be fast!
• Tests should have a narrow scope
• Tests should not depend on other tests
Test Requirements
Wednesday, April 16, 14
Tests should not depend on other tests.
This is a big one.
Tests should not rely on state set by other tests.
You should be able to run your tests in random order with no surprises.
Coupling your tests together can make them slow, fragile, and error prone. Avoid coupled tests like the plague.
Kent Beck, Test Driven Development By Example (awesome book), big slow tests
• Tests should be fast!
• Tests should have a narrow scope
• Tests should not depend on other tests
• Do not test implementation details, only behavior
Test Requirements
Wednesday, April 16, 14
Test the behavior of your code.
Your tests exist to ensure the behavior of your code under test acts in a manor that you deem correct.
Micromanaging the smaller details becomes very tedious and leads to fragile tests.
Mocks
• Tests should be fast!
• Tests should have a narrow scope
• Tests should not depend on other tests
• Do not test implementation details, only behavior
• Be careful not to over-mock your tests!
Test Requirements
Wednesday, April 16, 14
Testing implementation details usually involves mocks
Mocks are great but easily abused
Over mocking leads to you actually testing the mocks as opposed to the code you really wanted to test.
Use your mocks/stubs/doubles judiciously.
I usually mock code when communicating with a third party service. In Chef this usually means mocking out Searching or inline
command within the guard statements in Chef providers. Chefspec does a great job of doing both of those things. You should
check out some of their examples online.
Types of Tests
Wednesday, April 16, 14
As I touched on earlier there are a couple of different kinds of tests. These different tests serve different purposes.
• Unit Testing - Single function testing
Types of Tests (Dev Side)
Wednesday, April 16, 14
In the dev world some of the common types of tests that we utilize are:
Simply put these tests should be lightning fast and test that your single function behaves as expected.
• Unit Testing - Single function testing
• Integration Testing - Interdependent modules testing
Types of Tests (Dev Side)
Wednesday, April 16, 14
Integration tests are the tests the components that make up a user story.
They’re a step above unit tests and should test the interaction between various parts of your codebase.
These tests should run fairly fast and test the correctness of your code.
These ensure that your code behaves well with others. When writing code I usually start with these then solidify and generalize
my design with unit tests
• Unit Testing - Single function testing
• Integration Testing - Interdependent modules testing
• Acceptance Testing - Black box/User Story testing
Types of Tests (Dev Side)
Wednesday, April 16, 14
Acceptance tests which test the user story the code is supposed to satisfy.
Black Box, request goes in - what comes out?
API example
These tests can be slow and the scope of the test can be pretty big sometimes. Try to keep the scope of the tests as wide as it
needs to be to satisfy a single user story.
• Unit Testing - Single recipe test assertions against Chef resource
collection
Chef Analogues
Wednesday, April 16, 14
Unit tests ensure that Chef resources are created as we expect via Chefspec. Fast tests
Not actually testing the “correctness” of the code, not the goal of unit tests.
Uncle Bob Martin - “The act of writing a unit test is more an act of design than of verification.  It is also more an act of
documentation than of verification.  The act of writing a unit test closes a remarkable number of feedback loops, the least of
which is the one pertaining to verification of function
These are used for ensuring refactoring doesn’t break anything.
• Unit Testing - Single recipe test assertions against Chef resource
collection
• Integration Testing - Single node post-convergence assertions
Chef Analogues
Wednesday, April 16, 14
Run against converged node via Test Kitchen and BATS
Test correctness of our recipe or recipes
Ensures everything plays nicely together and node is in a state we deem correct.
Be sure you don’t repeat the tests that you’ve written for your unit tests.
• Unit Testing - Single recipe test assertions against Chef resource
collection
• Integration Testing - Single node post-convergence assertions
• Acceptance Testing - Assertions against your infrastructure or subset
of it
Chef Analogues
Wednesday, April 16, 14
Subset of your infrastructure. Given your new node does it interact with other nodes as you expect?
New node should play nicely.
• Unit Testing - Chefspec / Rspec (for plain Ruby code)
• Integration Testing - BATS and Test Kitchen
• Acceptance Testing - ??? (Open to suggestions!)
Chef Testing Tools
Wednesday, April 16, 14
Chefspec/Rspec are great tools and easy to work with
Test Kitchen and BATS (Bash Automated Testing System) shell for tests. Actually really nice and clean.
In full disclosure we haven’t come up with a great way to write automated acceptance tests out at AWeber that we’re totally
satisfied with so if you have any recommendations I would love to hear about them.
Enter TDD
Wednesday, April 16, 14
At it’s simplest TDD is writing tests before writing code
Tests guide development of production code
Seemingly simple, but profound impact on code
Some of the benefits of TDD are...
• Forces code to be testable
Why TDD?
Wednesday, April 16, 14
Since we’re developing our code test first we now place a strong emphasis on writing testable code.
If we’re not writing testable code then our tests become a slow, horrible mess that no one will wants to run.
When tests become slow and fragile people won’t want to run them which totally defeats their purpose.
Make your tests fast.
Why TDD?
• Forces code to be testable
• Promotes loose code coupling
Wednesday, April 16, 14
Code become less interested in other implementation details of unrelated code.
Rely on public interfaces than implementation
Using functions or LWRPs instead of reproducing it’s contents. LDAP User creation example
Looser code coupling forces you to think about your codes public interface as opposed to its underlying implementation.
Why TDD?
• Forces code to be testable
• Promotes loose code coupling
• Confidence in production code
Wednesday, April 16, 14
Gaining confidence in the code we push means that we can push code faster and with minimal risk of our code going nuclear
leading to a nice little Pager storm.
Positive feedback loop vs Negative feedback loop
Why TDD?
• Forces code to be testable
• Promotes loose code coupling
• Confidence in production code
• Introduces a quick development feedback loop...
Wednesday, April 16, 14
One of the major benefits of developing code is the introduction of a really nice feedback loop. The Red Green Refactor cycle.
Red Green Refactor Cycle
Wednesday, April 16, 14
The red green refactor cycle.
Red - Write a failing test (only one). Motivates a new feature
Green - Make the failing test pass by writing production code
- Only write code needed to make test pass
Refactor - Clean up your mess
Writing a Test
(Red/Green states)
Wednesday, April 16, 14
Walk through the Red/Green states
Refactoring is harder
Writing a failing integration test
Wednesday, April 16, 14
This is BATS
Supervisor program called ‘my-api’
Non-zero exit status == success
Failing Integration test output
Wednesday, April 16, 14
Make sure your test fails before writing code to make it pass!
Writing a failing unit test
Wednesday, April 16, 14
Chefspec Unit Test
Custom matcher needed to get test to pass (by any means needed)
Tests Supervisor resource ‘my-api’ is created
BetterSpecs.org
Failing unit test output
Wednesday, April 16, 14
Making it pass
Wednesday, April 16, 14
Passing Integration test output
Wednesday, April 16, 14
Passing unit test output
Wednesday, April 16, 14
Awesome!
Wednesday, April 16, 14
We’re GREEN!
Refactoring
Wednesday, April 16, 14
Always Be Refactoring
Wednesday, April 16, 14
Refactoring is not a terminal state!
Why have an entirely separate state for refactoring?
• Cleaning up after your compromises getting tests to pass
Why Refactor?
Wednesday, April 16, 14
Liberties can be taken to get to the green state. Now it’s time to pay for your crimes.
• Cleaning up after your compromises getting tests to pass
• Paying down technical debt
Why Refactor?
Wednesday, April 16, 14
Refactoring can eliminate technical debt elsewhere in the codebase
• Cleaning up after your compromises getting tests to pass
• Paying down technical debt
• Makes software easier to understand
Why Refactor?
Wednesday, April 16, 14
“Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live.”
• Cleaning up after your compromises getting tests to pass
• Paying down technical debt
• Makes software easier to understand
• Eliminates duplication
Why Refactor?
Wednesday, April 16, 14
More on this later
How to Refactor
Wednesday, April 16, 14
• Isolate implementation behavior into LWRP, Function, etc
How do we refactor in Chef?
Wednesday, April 16, 14
Hide implementation details behind a nice interface either an LWRP or function
• Isolate implementation behavior into LWRP, Function, etc
• “Utility” cookbooks for similar behavior
How do we refactor in Chef?
Wednesday, April 16, 14
Isolate larger pieces of related functionality behind a separate cookbook.
Cookbooks with no recipes and only LWRPs and Functions are perfectly fine.
• Isolate implementation behavior into LWRP, Function, etc
• “Utility” cookbooks for similar behavior
• Library functions (and supporting Gems)
How do we refactor in Chef?
Wednesday, April 16, 14
How not to Refactor
Wednesday, April 16, 14
• Do not introduce new functionality while refactoring.
How don’t we refactor?
Wednesday, April 16, 14
Need a failing test first, go back to the red state
• Do not introduce new functionality while refactoring.
• Do not leave your tests in a broken state
How don’t we refactor?
Wednesday, April 16, 14
Need to be in the green state before going back to red
• Do not introduce new functionality while refactoring.
• Do not leave your tests in a broken state
• Don’t the skip the refactoring step!
How don’t we refactor?
Wednesday, April 16, 14
Eliminating Duplication
Wednesday, April 16, 14
• Duplication is evil!
Why eliminate duplication?
Wednesday, April 16, 14
• Duplication is evil!
• Keep your code DRY!
Why eliminate duplication?
Wednesday, April 16, 14
• Duplication is evil!
• Keep your code DRY!
• Multiple places to maintain when requirements change
Why eliminate duplication?
Wednesday, April 16, 14
• Duplication is evil!
• Keep your code DRY!
• Multiple places to maintain when requirements change
• Repetition eventually leads to inconsistency in the codebase
Why eliminate duplication?
Wednesday, April 16, 14
Back to the Red State
Wednesday, April 16, 14
Tightening the
feedback loop
Wednesday, April 16, 14
Guard
• Rspec Guard for Chefspec tests
• Kitchen Guard for Test Kitchen tests
Wednesday, April 16, 14
TL;DR
• Try out TDD to see if it works for you
• DON’T Commit copied and pasted code
• DON’T Forget to refactor your code and your tests
• DON’T Forget to see your test fail first!
Wednesday, April 16, 14
Questions?
Wednesday, April 16, 14
• Photo Credits
• http://en.wikipedia.org/wiki/File:Operation_Upshot-Knothole_-_Badger_001.jpg
• http://agileinaflash.blogspot.com/2009/02/red-green-refactor.html
• http://twentytwowords.com/guns-in-movies-replaced-with-thumbs-ups-15-pictures/
• http://stfalcon.com/blog/post/phpstorm-refactoring
• http://guardgem.org/
Wednesday, April 16, 14

More Related Content

What's hot

End-to-end performance testing, profiling, and analysis at Redis
End-to-end performance testing, profiling, and analysis at RedisEnd-to-end performance testing, profiling, and analysis at Redis
End-to-end performance testing, profiling, and analysis at RedisFilipe Oliveira
 
Continuous Integration: Finding problems soonest
Continuous Integration: Finding problems soonestContinuous Integration: Finding problems soonest
Continuous Integration: Finding problems soonestShawn Jones
 
АННА ТИМОФІЄВА & СЕРГІЙ МАЛИНОВСЬКИЙ «Tools and Tips of video connection test...
АННА ТИМОФІЄВА & СЕРГІЙ МАЛИНОВСЬКИЙ «Tools and Tips of video connection test...АННА ТИМОФІЄВА & СЕРГІЙ МАЛИНОВСЬКИЙ «Tools and Tips of video connection test...
АННА ТИМОФІЄВА & СЕРГІЙ МАЛИНОВСЬКИЙ «Tools and Tips of video connection test...GoQA
 
АНТОН МУЖАЙЛО «Test Team Development and Management Techniques»
АНТОН МУЖАЙЛО «Test Team Development and Management Techniques»АНТОН МУЖАЙЛО «Test Team Development and Management Techniques»
АНТОН МУЖАЙЛО «Test Team Development and Management Techniques»GoQA
 
Test Driven Development on Android (Kotlin Kenya)
Test Driven Development on Android (Kotlin Kenya)Test Driven Development on Android (Kotlin Kenya)
Test Driven Development on Android (Kotlin Kenya)Danny Preussler
 
End-to-End Automated Testing: Lessons from Zombieland
End-to-End Automated Testing: Lessons from ZombielandEnd-to-End Automated Testing: Lessons from Zombieland
End-to-End Automated Testing: Lessons from ZombielandJosiah Renaudin
 
How do you tame a big ball of mud? One test at a time.
How do you tame a big ball of mud? One test at a time.How do you tame a big ball of mud? One test at a time.
How do you tame a big ball of mud? One test at a time.Matt Eland
 
Writing useful automated tests for the single page applications you build
Writing useful automated tests for the single page applications you buildWriting useful automated tests for the single page applications you build
Writing useful automated tests for the single page applications you buildAndrei Sebastian Cîmpean
 
TDD for Testers Workshop
TDD for Testers WorkshopTDD for Testers Workshop
TDD for Testers WorkshopSarah Usher
 
Code Review: How and When
Code Review: How and WhenCode Review: How and When
Code Review: How and WhenPaul Gower
 
Lessons Learned in Test Automation From Zombieland
Lessons Learned in Test Automation From ZombielandLessons Learned in Test Automation From Zombieland
Lessons Learned in Test Automation From ZombielandMatt Barbour
 
A journey to a Full Stack Tester
A journey to a Full Stack Tester A journey to a Full Stack Tester
A journey to a Full Stack Tester KMS Technology
 
Build Your Mobile App Quality and Test Strategy
Build Your Mobile App Quality and Test StrategyBuild Your Mobile App Quality and Test Strategy
Build Your Mobile App Quality and Test StrategyTechWell
 
How to be proud when you are done
How to be proud when you are doneHow to be proud when you are done
How to be proud when you are doneAleksey Solntsev
 
Continuous delivery its not about the technology, its about the people.
Continuous delivery its not about the technology, its about the people.Continuous delivery its not about the technology, its about the people.
Continuous delivery its not about the technology, its about the people.Tomas Riha
 
Continuous delivery its not about the technology, its about the people. @pipe...
Continuous delivery its not about the technology, its about the people. @pipe...Continuous delivery its not about the technology, its about the people. @pipe...
Continuous delivery its not about the technology, its about the people. @pipe...Tomas Riha
 

What's hot (20)

End-to-end performance testing, profiling, and analysis at Redis
End-to-end performance testing, profiling, and analysis at RedisEnd-to-end performance testing, profiling, and analysis at Redis
End-to-end performance testing, profiling, and analysis at Redis
 
Continuous Integration: Finding problems soonest
Continuous Integration: Finding problems soonestContinuous Integration: Finding problems soonest
Continuous Integration: Finding problems soonest
 
АННА ТИМОФІЄВА & СЕРГІЙ МАЛИНОВСЬКИЙ «Tools and Tips of video connection test...
АННА ТИМОФІЄВА & СЕРГІЙ МАЛИНОВСЬКИЙ «Tools and Tips of video connection test...АННА ТИМОФІЄВА & СЕРГІЙ МАЛИНОВСЬКИЙ «Tools and Tips of video connection test...
АННА ТИМОФІЄВА & СЕРГІЙ МАЛИНОВСЬКИЙ «Tools and Tips of video connection test...
 
АНТОН МУЖАЙЛО «Test Team Development and Management Techniques»
АНТОН МУЖАЙЛО «Test Team Development and Management Techniques»АНТОН МУЖАЙЛО «Test Team Development and Management Techniques»
АНТОН МУЖАЙЛО «Test Team Development and Management Techniques»
 
Test Driven Development on Android (Kotlin Kenya)
Test Driven Development on Android (Kotlin Kenya)Test Driven Development on Android (Kotlin Kenya)
Test Driven Development on Android (Kotlin Kenya)
 
End-to-End Automated Testing: Lessons from Zombieland
End-to-End Automated Testing: Lessons from ZombielandEnd-to-End Automated Testing: Lessons from Zombieland
End-to-End Automated Testing: Lessons from Zombieland
 
How do you tame a big ball of mud? One test at a time.
How do you tame a big ball of mud? One test at a time.How do you tame a big ball of mud? One test at a time.
How do you tame a big ball of mud? One test at a time.
 
Writing useful automated tests for the single page applications you build
Writing useful automated tests for the single page applications you buildWriting useful automated tests for the single page applications you build
Writing useful automated tests for the single page applications you build
 
TDD for Testers Workshop
TDD for Testers WorkshopTDD for Testers Workshop
TDD for Testers Workshop
 
Code Review: How and When
Code Review: How and WhenCode Review: How and When
Code Review: How and When
 
Lessons Learned in Test Automation From Zombieland
Lessons Learned in Test Automation From ZombielandLessons Learned in Test Automation From Zombieland
Lessons Learned in Test Automation From Zombieland
 
A journey to a Full Stack Tester
A journey to a Full Stack Tester A journey to a Full Stack Tester
A journey to a Full Stack Tester
 
Build Your Mobile App Quality and Test Strategy
Build Your Mobile App Quality and Test StrategyBuild Your Mobile App Quality and Test Strategy
Build Your Mobile App Quality and Test Strategy
 
How to be proud when you are done
How to be proud when you are doneHow to be proud when you are done
How to be proud when you are done
 
Continuous delivery its not about the technology, its about the people.
Continuous delivery its not about the technology, its about the people.Continuous delivery its not about the technology, its about the people.
Continuous delivery its not about the technology, its about the people.
 
Automation and Technical Debt
Automation and Technical DebtAutomation and Technical Debt
Automation and Technical Debt
 
PL/SQL unit testing with Ruby
PL/SQL unit testing with RubyPL/SQL unit testing with Ruby
PL/SQL unit testing with Ruby
 
Code review
Code reviewCode review
Code review
 
Continuous delivery its not about the technology, its about the people. @pipe...
Continuous delivery its not about the technology, its about the people. @pipe...Continuous delivery its not about the technology, its about the people. @pipe...
Continuous delivery its not about the technology, its about the people. @pipe...
 
XP Injection
XP InjectionXP Injection
XP Injection
 

Viewers also liked

Leveraging Social Media Tools
Leveraging Social Media ToolsLeveraging Social Media Tools
Leveraging Social Media ToolsSage Island
 
Grafico diario del dax perfomance index para el 07 11-2012
Grafico diario del dax perfomance index para el 07 11-2012Grafico diario del dax perfomance index para el 07 11-2012
Grafico diario del dax perfomance index para el 07 11-2012Experiencia Trading
 
حملة عمر بلدك
حملة عمر بلدكحملة عمر بلدك
حملة عمر بلدكAlaa Wahba
 
There's No Crying In Local Search
There's No Crying In Local SearchThere's No Crying In Local Search
There's No Crying In Local SearchGreg Gifford
 
Digitalisaatio ja valtioneuvosto
Digitalisaatio ja valtioneuvostoDigitalisaatio ja valtioneuvosto
Digitalisaatio ja valtioneuvostoJyrki Kasvi
 
Презентация устройства "Корден"
Презентация устройства "Корден"Презентация устройства "Корден"
Презентация устройства "Корден"kulibin
 
Defining classes-and-objects-1.0
Defining classes-and-objects-1.0Defining classes-and-objects-1.0
Defining classes-and-objects-1.0BG Java EE Course
 
On the frontier of genotype-2-phenotype data integration
On the frontier of genotype-2-phenotype data integrationOn the frontier of genotype-2-phenotype data integration
On the frontier of genotype-2-phenotype data integrationmhaendel
 

Viewers also liked (20)

Leveraging Social Media Tools
Leveraging Social Media ToolsLeveraging Social Media Tools
Leveraging Social Media Tools
 
Grafico diario del dax perfomance index para el 07 11-2012
Grafico diario del dax perfomance index para el 07 11-2012Grafico diario del dax perfomance index para el 07 11-2012
Grafico diario del dax perfomance index para el 07 11-2012
 
حملة عمر بلدك
حملة عمر بلدكحملة عمر بلدك
حملة عمر بلدك
 
Estudiante virtual exioso
Estudiante virtual exiosoEstudiante virtual exioso
Estudiante virtual exioso
 
About the-course
About the-courseAbout the-course
About the-course
 
Methods intro-1.0
Methods intro-1.0Methods intro-1.0
Methods intro-1.0
 
World Economic Forum on Africa 2006
World Economic Forum on Africa 2006World Economic Forum on Africa 2006
World Economic Forum on Africa 2006
 
There's No Crying In Local Search
There's No Crying In Local SearchThere's No Crying In Local Search
There's No Crying In Local Search
 
Espirometría
EspirometríaEspirometría
Espirometría
 
Καινοτομια
ΚαινοτομιαΚαινοτομια
Καινοτομια
 
Adobe Flash, entre el amor y el odio
Adobe Flash, entre el amor y el odioAdobe Flash, entre el amor y el odio
Adobe Flash, entre el amor y el odio
 
Digitalisaatio ja valtioneuvosto
Digitalisaatio ja valtioneuvostoDigitalisaatio ja valtioneuvosto
Digitalisaatio ja valtioneuvosto
 
書籍市場の現状
書籍市場の現状書籍市場の現状
書籍市場の現状
 
Презентация устройства "Корден"
Презентация устройства "Корден"Презентация устройства "Корден"
Презентация устройства "Корден"
 
Defining classes-and-objects-1.0
Defining classes-and-objects-1.0Defining classes-and-objects-1.0
Defining classes-and-objects-1.0
 
Basic computer
Basic computerBasic computer
Basic computer
 
On the frontier of genotype-2-phenotype data integration
On the frontier of genotype-2-phenotype data integrationOn the frontier of genotype-2-phenotype data integration
On the frontier of genotype-2-phenotype data integration
 
LESTER_ANTONY_FRANCIS ( Aug 2016)
LESTER_ANTONY_FRANCIS ( Aug 2016)LESTER_ANTONY_FRANCIS ( Aug 2016)
LESTER_ANTONY_FRANCIS ( Aug 2016)
 
Teatro s. XVII
Teatro s. XVIITeatro s. XVII
Teatro s. XVII
 
Talk nerdy to me!
Talk nerdy to me!Talk nerdy to me!
Talk nerdy to me!
 

Similar to ChefConf2014 - Chef TDD

May 2021 Spark Testing ... or how to farm reputation on StackOverflow
May 2021 Spark Testing ... or how to farm reputation on StackOverflowMay 2021 Spark Testing ... or how to farm reputation on StackOverflow
May 2021 Spark Testing ... or how to farm reputation on StackOverflowAdam Doyle
 
Agile testingandautomation
Agile testingandautomationAgile testingandautomation
Agile testingandautomationjeisner
 
Moving to Continuous Delivery Without Breaking Your Code
Moving to Continuous Delivery Without Breaking Your CodeMoving to Continuous Delivery Without Breaking Your Code
Moving to Continuous Delivery Without Breaking Your CodeXebiaLabs
 
Test Driven Development with Laravel
Test Driven Development with LaravelTest Driven Development with Laravel
Test Driven Development with LaravelTyler Johnston
 
iOS Test-Driven Development
iOS Test-Driven DevelopmentiOS Test-Driven Development
iOS Test-Driven DevelopmentPablo Villar
 
Completely Test-Driven
Completely Test-DrivenCompletely Test-Driven
Completely Test-DrivenIan Truslove
 
TDD — Are you sure you properly test code?
TDD — Are you sure you properly test code?TDD — Are you sure you properly test code?
TDD — Are you sure you properly test code?Dmitriy Nesteryuk
 
Move test planning before implementation
Move test planning before implementationMove test planning before implementation
Move test planning before implementationTed Cheng
 
Getting started with Test Driven Development - Ferdous Mahmud Shaon
Getting started with Test Driven Development - Ferdous Mahmud ShaonGetting started with Test Driven Development - Ferdous Mahmud Shaon
Getting started with Test Driven Development - Ferdous Mahmud ShaonCefalo
 
Getting started with Test Driven Development
Getting started with Test Driven DevelopmentGetting started with Test Driven Development
Getting started with Test Driven DevelopmentFerdous Mahmud Shaon
 
Test Drive Development
Test Drive DevelopmentTest Drive Development
Test Drive Developmentsatya sudheer
 
Start with passing tests (tdd for bugs) v0.5 (22 sep 2016)
Start with passing tests (tdd for bugs) v0.5 (22 sep 2016)Start with passing tests (tdd for bugs) v0.5 (22 sep 2016)
Start with passing tests (tdd for bugs) v0.5 (22 sep 2016)Dinis Cruz
 
A Brief Introduction to Test-Driven Development
A Brief Introduction to Test-Driven DevelopmentA Brief Introduction to Test-Driven Development
A Brief Introduction to Test-Driven DevelopmentShawn Jones
 
Intro TDD Portuguese developers meetup London 16/04/2014
Intro TDD Portuguese developers meetup London 16/04/2014Intro TDD Portuguese developers meetup London 16/04/2014
Intro TDD Portuguese developers meetup London 16/04/2014Pedro Santos
 
Unit Testing and Behavior Driven Testing with AngularJS - Jesse Liberty | Fal...
Unit Testing and Behavior Driven Testing with AngularJS - Jesse Liberty | Fal...Unit Testing and Behavior Driven Testing with AngularJS - Jesse Liberty | Fal...
Unit Testing and Behavior Driven Testing with AngularJS - Jesse Liberty | Fal...FalafelSoftware
 
An Introduction To Software Development - Test Driven Development, Part 1
An Introduction To Software Development - Test Driven Development, Part 1An Introduction To Software Development - Test Driven Development, Part 1
An Introduction To Software Development - Test Driven Development, Part 1Blue Elephant Consulting
 

Similar to ChefConf2014 - Chef TDD (20)

May 2021 Spark Testing ... or how to farm reputation on StackOverflow
May 2021 Spark Testing ... or how to farm reputation on StackOverflowMay 2021 Spark Testing ... or how to farm reputation on StackOverflow
May 2021 Spark Testing ... or how to farm reputation on StackOverflow
 
Unit testing in PHP
Unit testing in PHPUnit testing in PHP
Unit testing in PHP
 
Intro to TDD
Intro to TDDIntro to TDD
Intro to TDD
 
Agile testingandautomation
Agile testingandautomationAgile testingandautomation
Agile testingandautomation
 
Moving to Continuous Delivery Without Breaking Your Code
Moving to Continuous Delivery Without Breaking Your CodeMoving to Continuous Delivery Without Breaking Your Code
Moving to Continuous Delivery Without Breaking Your Code
 
Test Driven Development with Laravel
Test Driven Development with LaravelTest Driven Development with Laravel
Test Driven Development with Laravel
 
iOS Test-Driven Development
iOS Test-Driven DevelopmentiOS Test-Driven Development
iOS Test-Driven Development
 
Completely Test-Driven
Completely Test-DrivenCompletely Test-Driven
Completely Test-Driven
 
TDD — Are you sure you properly test code?
TDD — Are you sure you properly test code?TDD — Are you sure you properly test code?
TDD — Are you sure you properly test code?
 
Move test planning before implementation
Move test planning before implementationMove test planning before implementation
Move test planning before implementation
 
Getting started with Test Driven Development - Ferdous Mahmud Shaon
Getting started with Test Driven Development - Ferdous Mahmud ShaonGetting started with Test Driven Development - Ferdous Mahmud Shaon
Getting started with Test Driven Development - Ferdous Mahmud Shaon
 
Getting started with Test Driven Development
Getting started with Test Driven DevelopmentGetting started with Test Driven Development
Getting started with Test Driven Development
 
Test Drive Development
Test Drive DevelopmentTest Drive Development
Test Drive Development
 
Start with passing tests (tdd for bugs) v0.5 (22 sep 2016)
Start with passing tests (tdd for bugs) v0.5 (22 sep 2016)Start with passing tests (tdd for bugs) v0.5 (22 sep 2016)
Start with passing tests (tdd for bugs) v0.5 (22 sep 2016)
 
A Brief Introduction to Test-Driven Development
A Brief Introduction to Test-Driven DevelopmentA Brief Introduction to Test-Driven Development
A Brief Introduction to Test-Driven Development
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven Development
 
Intro TDD Portuguese developers meetup London 16/04/2014
Intro TDD Portuguese developers meetup London 16/04/2014Intro TDD Portuguese developers meetup London 16/04/2014
Intro TDD Portuguese developers meetup London 16/04/2014
 
Unit Testing and Behavior Driven Testing with AngularJS - Jesse Liberty | Fal...
Unit Testing and Behavior Driven Testing with AngularJS - Jesse Liberty | Fal...Unit Testing and Behavior Driven Testing with AngularJS - Jesse Liberty | Fal...
Unit Testing and Behavior Driven Testing with AngularJS - Jesse Liberty | Fal...
 
TDD and Getting Paid
TDD and Getting PaidTDD and Getting Paid
TDD and Getting Paid
 
An Introduction To Software Development - Test Driven Development, Part 1
An Introduction To Software Development - Test Driven Development, Part 1An Introduction To Software Development - Test Driven Development, Part 1
An Introduction To Software Development - Test Driven Development, Part 1
 

Recently uploaded

A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?XfilesPro
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksSoftradix Technologies
 

Recently uploaded (20)

A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping Elbows
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other Frameworks
 

ChefConf2014 - Chef TDD

  • 1. Chef TDD (how I learned to stop worrying and love to test. Wednesday, April 16, 14
  • 2. • Dan Tracy • Software Engineer at AWeber Communications • Primarily a Python developer • Github - djt5019 <https://github.com/djt5019> • twitter - @djt5019 Who Am I? Wednesday, April 16, 14 My name is Dan Tracy and I am a software engineer over at AWeber Communications. I am primarily a python dev on backend apps. Dev work always in TDD - reject untested pull requests Became interested in Chef some time ago rougher tools, testing mentality not rooted Ops had slow, manual, fragile tests Introduced TDD - Hit some roadbumps - Highlighted some Infra issues - look at skeletons in our closet - Otherwise very successful
  • 3. Why Test? Wednesday, April 16, 14 Why should we even test in the first place? What is being gained from testing? Is it even worth our time? Hell yes it is.
  • 4. Wednesday, April 16, 14 When you begin writing tests you eventually develop a distaste for untested code.
  • 5. Why Test? • Minimizing risk Wednesday, April 16, 14 Minimizing risk we throw over the fence when we deploy our changes Breaking out of the negative feedback loop of being too scared to make changes Entering a positive feedback loop where we can iterate on our code quickly Faster to market with new features
  • 6. Why Test? • Minimizing risk • Confidence in what we write Wednesday, April 16, 14 When we minimize risk we develop confidence in our codebase, if we have confidence in what we write we are inclined to deploy it faster. Positive feedback loop when confident Negative feedback loop when not confident
  • 7. Why Test? • Minimizing risk • Confidence in what we write • Ensure that we’re pushing out good code Wednesday, April 16, 14 When we have tests we have a fairweather indicator that our changes didn’t break anything else.
  • 8. Don’t want this Wednesday, April 16, 14 This is what your untested code does at 3am.
  • 9. Requirements for Testing Wednesday, April 16, 14 Now you’re convinced and ready to write some tests need to know requirements for writing tests
  • 10. • Tests should be fast! Test Requirements Wednesday, April 16, 14 Tests should be fast. The word fast is relative to the types of tests that we’re running. There will be more unit tests than integration tests, and more integration tests than acceptance tests. Negative feedback loop for slow tests
  • 11. • Tests should be fast! • Tests should have a narrow scope Test Requirements Wednesday, April 16, 14 Tests should have a narrow scope. Test bare minimum needed to satisfy your requirements. Your function, LWRP, or code under test should be doing only one thing and doing it well.
  • 12. • Tests should be fast! • Tests should have a narrow scope • Tests should not depend on other tests Test Requirements Wednesday, April 16, 14 Tests should not depend on other tests. This is a big one. Tests should not rely on state set by other tests. You should be able to run your tests in random order with no surprises. Coupling your tests together can make them slow, fragile, and error prone. Avoid coupled tests like the plague. Kent Beck, Test Driven Development By Example (awesome book), big slow tests
  • 13. • Tests should be fast! • Tests should have a narrow scope • Tests should not depend on other tests • Do not test implementation details, only behavior Test Requirements Wednesday, April 16, 14 Test the behavior of your code. Your tests exist to ensure the behavior of your code under test acts in a manor that you deem correct. Micromanaging the smaller details becomes very tedious and leads to fragile tests. Mocks
  • 14. • Tests should be fast! • Tests should have a narrow scope • Tests should not depend on other tests • Do not test implementation details, only behavior • Be careful not to over-mock your tests! Test Requirements Wednesday, April 16, 14 Testing implementation details usually involves mocks Mocks are great but easily abused Over mocking leads to you actually testing the mocks as opposed to the code you really wanted to test. Use your mocks/stubs/doubles judiciously. I usually mock code when communicating with a third party service. In Chef this usually means mocking out Searching or inline command within the guard statements in Chef providers. Chefspec does a great job of doing both of those things. You should check out some of their examples online.
  • 15. Types of Tests Wednesday, April 16, 14 As I touched on earlier there are a couple of different kinds of tests. These different tests serve different purposes.
  • 16. • Unit Testing - Single function testing Types of Tests (Dev Side) Wednesday, April 16, 14 In the dev world some of the common types of tests that we utilize are: Simply put these tests should be lightning fast and test that your single function behaves as expected.
  • 17. • Unit Testing - Single function testing • Integration Testing - Interdependent modules testing Types of Tests (Dev Side) Wednesday, April 16, 14 Integration tests are the tests the components that make up a user story. They’re a step above unit tests and should test the interaction between various parts of your codebase. These tests should run fairly fast and test the correctness of your code. These ensure that your code behaves well with others. When writing code I usually start with these then solidify and generalize my design with unit tests
  • 18. • Unit Testing - Single function testing • Integration Testing - Interdependent modules testing • Acceptance Testing - Black box/User Story testing Types of Tests (Dev Side) Wednesday, April 16, 14 Acceptance tests which test the user story the code is supposed to satisfy. Black Box, request goes in - what comes out? API example These tests can be slow and the scope of the test can be pretty big sometimes. Try to keep the scope of the tests as wide as it needs to be to satisfy a single user story.
  • 19. • Unit Testing - Single recipe test assertions against Chef resource collection Chef Analogues Wednesday, April 16, 14 Unit tests ensure that Chef resources are created as we expect via Chefspec. Fast tests Not actually testing the “correctness” of the code, not the goal of unit tests. Uncle Bob Martin - “The act of writing a unit test is more an act of design than of verification.  It is also more an act of documentation than of verification.  The act of writing a unit test closes a remarkable number of feedback loops, the least of which is the one pertaining to verification of function These are used for ensuring refactoring doesn’t break anything.
  • 20. • Unit Testing - Single recipe test assertions against Chef resource collection • Integration Testing - Single node post-convergence assertions Chef Analogues Wednesday, April 16, 14 Run against converged node via Test Kitchen and BATS Test correctness of our recipe or recipes Ensures everything plays nicely together and node is in a state we deem correct. Be sure you don’t repeat the tests that you’ve written for your unit tests.
  • 21. • Unit Testing - Single recipe test assertions against Chef resource collection • Integration Testing - Single node post-convergence assertions • Acceptance Testing - Assertions against your infrastructure or subset of it Chef Analogues Wednesday, April 16, 14 Subset of your infrastructure. Given your new node does it interact with other nodes as you expect? New node should play nicely.
  • 22. • Unit Testing - Chefspec / Rspec (for plain Ruby code) • Integration Testing - BATS and Test Kitchen • Acceptance Testing - ??? (Open to suggestions!) Chef Testing Tools Wednesday, April 16, 14 Chefspec/Rspec are great tools and easy to work with Test Kitchen and BATS (Bash Automated Testing System) shell for tests. Actually really nice and clean. In full disclosure we haven’t come up with a great way to write automated acceptance tests out at AWeber that we’re totally satisfied with so if you have any recommendations I would love to hear about them.
  • 23. Enter TDD Wednesday, April 16, 14 At it’s simplest TDD is writing tests before writing code Tests guide development of production code Seemingly simple, but profound impact on code Some of the benefits of TDD are...
  • 24. • Forces code to be testable Why TDD? Wednesday, April 16, 14 Since we’re developing our code test first we now place a strong emphasis on writing testable code. If we’re not writing testable code then our tests become a slow, horrible mess that no one will wants to run. When tests become slow and fragile people won’t want to run them which totally defeats their purpose. Make your tests fast.
  • 25. Why TDD? • Forces code to be testable • Promotes loose code coupling Wednesday, April 16, 14 Code become less interested in other implementation details of unrelated code. Rely on public interfaces than implementation Using functions or LWRPs instead of reproducing it’s contents. LDAP User creation example Looser code coupling forces you to think about your codes public interface as opposed to its underlying implementation.
  • 26. Why TDD? • Forces code to be testable • Promotes loose code coupling • Confidence in production code Wednesday, April 16, 14 Gaining confidence in the code we push means that we can push code faster and with minimal risk of our code going nuclear leading to a nice little Pager storm. Positive feedback loop vs Negative feedback loop
  • 27. Why TDD? • Forces code to be testable • Promotes loose code coupling • Confidence in production code • Introduces a quick development feedback loop... Wednesday, April 16, 14 One of the major benefits of developing code is the introduction of a really nice feedback loop. The Red Green Refactor cycle.
  • 28. Red Green Refactor Cycle Wednesday, April 16, 14 The red green refactor cycle. Red - Write a failing test (only one). Motivates a new feature Green - Make the failing test pass by writing production code - Only write code needed to make test pass Refactor - Clean up your mess
  • 29. Writing a Test (Red/Green states) Wednesday, April 16, 14 Walk through the Red/Green states Refactoring is harder
  • 30. Writing a failing integration test Wednesday, April 16, 14 This is BATS Supervisor program called ‘my-api’ Non-zero exit status == success
  • 31. Failing Integration test output Wednesday, April 16, 14 Make sure your test fails before writing code to make it pass!
  • 32. Writing a failing unit test Wednesday, April 16, 14 Chefspec Unit Test Custom matcher needed to get test to pass (by any means needed) Tests Supervisor resource ‘my-api’ is created BetterSpecs.org
  • 33. Failing unit test output Wednesday, April 16, 14
  • 35. Passing Integration test output Wednesday, April 16, 14
  • 36. Passing unit test output Wednesday, April 16, 14
  • 37. Awesome! Wednesday, April 16, 14 We’re GREEN!
  • 39. Always Be Refactoring Wednesday, April 16, 14 Refactoring is not a terminal state! Why have an entirely separate state for refactoring?
  • 40. • Cleaning up after your compromises getting tests to pass Why Refactor? Wednesday, April 16, 14 Liberties can be taken to get to the green state. Now it’s time to pay for your crimes.
  • 41. • Cleaning up after your compromises getting tests to pass • Paying down technical debt Why Refactor? Wednesday, April 16, 14 Refactoring can eliminate technical debt elsewhere in the codebase
  • 42. • Cleaning up after your compromises getting tests to pass • Paying down technical debt • Makes software easier to understand Why Refactor? Wednesday, April 16, 14 “Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live.”
  • 43. • Cleaning up after your compromises getting tests to pass • Paying down technical debt • Makes software easier to understand • Eliminates duplication Why Refactor? Wednesday, April 16, 14 More on this later
  • 45. • Isolate implementation behavior into LWRP, Function, etc How do we refactor in Chef? Wednesday, April 16, 14 Hide implementation details behind a nice interface either an LWRP or function
  • 46. • Isolate implementation behavior into LWRP, Function, etc • “Utility” cookbooks for similar behavior How do we refactor in Chef? Wednesday, April 16, 14 Isolate larger pieces of related functionality behind a separate cookbook. Cookbooks with no recipes and only LWRPs and Functions are perfectly fine.
  • 47. • Isolate implementation behavior into LWRP, Function, etc • “Utility” cookbooks for similar behavior • Library functions (and supporting Gems) How do we refactor in Chef? Wednesday, April 16, 14
  • 48. How not to Refactor Wednesday, April 16, 14
  • 49. • Do not introduce new functionality while refactoring. How don’t we refactor? Wednesday, April 16, 14 Need a failing test first, go back to the red state
  • 50. • Do not introduce new functionality while refactoring. • Do not leave your tests in a broken state How don’t we refactor? Wednesday, April 16, 14 Need to be in the green state before going back to red
  • 51. • Do not introduce new functionality while refactoring. • Do not leave your tests in a broken state • Don’t the skip the refactoring step! How don’t we refactor? Wednesday, April 16, 14
  • 53. • Duplication is evil! Why eliminate duplication? Wednesday, April 16, 14
  • 54. • Duplication is evil! • Keep your code DRY! Why eliminate duplication? Wednesday, April 16, 14
  • 55. • Duplication is evil! • Keep your code DRY! • Multiple places to maintain when requirements change Why eliminate duplication? Wednesday, April 16, 14
  • 56. • Duplication is evil! • Keep your code DRY! • Multiple places to maintain when requirements change • Repetition eventually leads to inconsistency in the codebase Why eliminate duplication? Wednesday, April 16, 14
  • 57. Back to the Red State Wednesday, April 16, 14
  • 59. Guard • Rspec Guard for Chefspec tests • Kitchen Guard for Test Kitchen tests Wednesday, April 16, 14
  • 60. TL;DR • Try out TDD to see if it works for you • DON’T Commit copied and pasted code • DON’T Forget to refactor your code and your tests • DON’T Forget to see your test fail first! Wednesday, April 16, 14
  • 62. • Photo Credits • http://en.wikipedia.org/wiki/File:Operation_Upshot-Knothole_-_Badger_001.jpg • http://agileinaflash.blogspot.com/2009/02/red-green-refactor.html • http://twentytwowords.com/guns-in-movies-replaced-with-thumbs-ups-15-pictures/ • http://stfalcon.com/blog/post/phpstorm-refactoring • http://guardgem.org/ Wednesday, April 16, 14