Efficient Rails Test-Driven
       Development

     Wolfram Arnold
    www.rubyfocus.biz

    In collaboration with:
Sarah Allen, BlazingCloud.net
       marakana.com
Class Outline

Week #1
  The economics of testing
  Testing in layers, design patterns
  Toolbox: RSpec with Rails
  RSpec & Models


Week #2
  A culture of testing: Why TDD? How to TDD?
  Testing & Data Dependencies
  Toolbox: Fixtures, Factories, Mocks & Stubs
Class Outline

Week #3
  Controller testing
  View, Helper, Routes Testing
  How much is enough? How much is too much?


Week #4
  Refactoring code & tests, custom matchers
  API Testing
  Remote data setup
  Cucumber for API testing & documentation
Class Outline

Week #5
  Integration Testing—when and how?
  Toolbox: Cucumber, Selenium & Friends
  Page Object Pattern


Week #6
  TDD—what next?
  BDD, Agile Process, XP → VDD: Value-Driven
   Development
  Advanced/Special Requests
What you can expect

Presentation, Examples
Answers to questions
A range of material from current development
  practice
Homework
Fluidity & adaptability
Fun
It works best, when...

Active participation
Try something new
Focus
Team Effort
  Pairing
  Utilizing the resources in class: TA's, participants
Discussions in public
  Class Q&A
  Mailing list
Efficient Rails Test-Driven
       Development
Why “efficient” and “testing”?

“Testing takes too much time.”
“It's more efficient to test later.”
“Testing is the responsibility of QA, not
  developers.”
“It's not practical to test X.”
   Tests break when data changes.
   Tests break when design changes.
The Role of Testing

Development without tests...
  fails to empower developers to efficiently take
    responsibility for quality of the code delivered
  makes collaboration harder
  build narrow silos of expertise
  instills fear & resistance to change
  makes documentation a chore
  stops being efficient very soon
TDD: Keeping cost of change low
Cost per change
                              without
                               TDD




                                  with
                                  TDD




                                   Time
Why?

Non-TDD
 Accumulates “technical debt” unchecked
 Removal of technical debt carries risk
    The more technical debt, the higher the risk
 Existing technical debt attracts more technical debt
    Like compound interest
    People are most likely to do what others did before them
    To break the pattern heroic discipline & coordination
      required
Testing in Layers

 Application, Browser UI           Selenium


                              RSpec Integration       Test::Unit Integration
   Application, Server
                              Cucumber, Webrat

                            RSpec           RSpec
 Views           Helpers
                            Views           Helpers

                            RSpec           RSpec     Test::Unit Functional
Controller       Routes
                           Controller       Routes

                                    RSpec             Test::Unit
         Model
                                    Model
Cost of Testing
                           Layers


 Application, Browser UI



   Application, Server



 Views           Helpers



Controller       Routes



         Model



                                    Cost
Cost of Testing
                           Relationship to data


                           most
 Application, Browser UI   removed


   Application, Server



 Views           Helpers



Controller       Routes



         Model             closest



                                                  Cost
Best ROI for Testing
                           Layers


 Application, Browser UI



   Application, Server



 Views           Helpers



Controller       Routes



         Model



                                    Impact/Line of Test Code
TDD & Design Patterns

Skinny Controller—   ➢   Designed to move logic
 Fat Model               from higher to lower
DRY                      application layers
named_scope          ➢   Following design
                         patterns makes testing
Proxy Associations       easier
Validations          ➢   Code written following
...                      TDD economics will
                         naturally converge on
                         these design patterns!
Structure of Tests

Setup
Expected value
Actual value
Verification: actual == expected?
Teardown
Good Tests are...

Compact
Responsible for testing one concern only
Fast
DRY
RSpec Verifications

should respond_to
should be_nil
   → works with any ? method (so-called “predicates”)
should be_valid
should_not be_nil; should_not be_valid
lambda {...}.should change(), {}, .from().to(), .by()
should eql, ==, equal
RSpec Structure

before, before(:each), before(:all)
after, after(:each), after(:all)
describe do...end, nested
it do... end
Let's do some coding

Demo
Models: What to test?

Validation Rules
Associations
Any custom method
Association Proxy Methods
Let's do some coding

Exercise, but wait...
Test-First Teaching

Pioneered by Sarah Allen
  Instructor writes tests
  Students write code


What about writing tests?
Behavior-First Teaching

Instructor specifies desired behavior
  in plain English
  like a user story
Students write tests
Students write code to make tests pass
Story Exercise #1

A Person object must have a first and last name.
A Person object can construct a full name from
  the first and last name.
A Person object has an optional middle name.
A Person object returns a full name including, if
  present, the middle name.
RSpec ==, eql, equal

obj.should == 5            5 == 5
obj.should eql(5)          5.eql 5
obj.should equal(5)        5.equal 5
Object Equality vs. Identity         Use ==
eql, ==      compare values          Unless you know you
                                     need something else
equal, === compare objects,
           classes

          Warning! Do not use != with RSpec.
          Use should_not instead.
RSpec should change

lambda {
  Person.create
}.should change(Person, :count).by(1)


lambda {
  @bob.addresses.create(:street => “...”)
}.should change(@bob.addresses, :count).by(1)

              nd
Warning: The 2 example is incorrect!
RSpec should change

lambda {
  # code that causes a change
}.should change(object, :method).by(difference)
or
should change(object,
  :method).from(initial).to(final)


The object typically is a class, if not, be wary of
 reload!
should change with block

lambda {
  # code that causes a change
}.should change { expression }.by(difference)
or
should change { expression }.from(initial).to(final)
better with block

lambda {
  @bob.addresses.create(:street => “...”)
}.should change {
  @bob.addresses(true).count }.by(1)
Homework

A Person should save correctly.
A Person can have many Addresses.
A Person's Address must have a street, city and
  zip.
A Person's Address can have an optional country.
If the country is left blank, it should default to
   “USA” prior to saving.
BizConf

                                Aug 4-6, 2010
                                Amelia Island, FL
                                Discount code: WOLF
Rails & Web App
Professionals, Entrepreneurs,
                                for 43% off
Consultants                     http://bizconf.org?
Small group                       coupon=WOLF
Network with Who's Who
Organized by Obie
Fernandez of Hashrocket
Highlight: David Allen

More Related Content

ODP
2010 07-20 TDD with ActiveResource
PDF
2011-02-03 LA RubyConf Rails3 TDD Workshop
PDF
Consuming REST services with ActiveResource
PDF
React && React Native workshop
PDF
Gemboys
PDF
Karate - powerful and simple framework for REST API automation testing
PPTX
Karate for Complex Web-Service API Testing by Peter Thomas
ODP
Introduction to Scala JS
2010 07-20 TDD with ActiveResource
2011-02-03 LA RubyConf Rails3 TDD Workshop
Consuming REST services with ActiveResource
React && React Native workshop
Gemboys
Karate - powerful and simple framework for REST API automation testing
Karate for Complex Web-Service API Testing by Peter Thomas
Introduction to Scala JS

What's hot (20)

PDF
Angular Application Testing
PDF
Karate - Web-Service API Testing Made Simple
PPTX
API Test Automation Using Karate (Anil Kumar Moka)
PPTX
Karate - MoT Dallas 26-Oct-2017
PDF
Real World Fun with ActiveResource
PPTX
Automate right start from API
PDF
Refactoring @ Mindvalley: Smells, Techniques and Patterns
PDF
Behavior Driven Development with Cucumber
PPTX
django Forms in a Web API World
PDF
BDD style Unit Testing
PDF
Using the latest Java Persistence API 2 Features - Tech Days 2010 India
PPTX
A Deep Dive into the W3C WebDriver Specification
PPTX
Karate DSL
PPTX
2016 - Serverless Microservices on AWS with API Gateway and Lambda
PDF
Metaprogramming JavaScript
PDF
Refactoring
PPTX
Introduction to testing in Rails
PDF
ExpertTalks Manchester September 2018
PDF
Ibm_interconnect_restapi_workshop
PDF
Cqrs api
Angular Application Testing
Karate - Web-Service API Testing Made Simple
API Test Automation Using Karate (Anil Kumar Moka)
Karate - MoT Dallas 26-Oct-2017
Real World Fun with ActiveResource
Automate right start from API
Refactoring @ Mindvalley: Smells, Techniques and Patterns
Behavior Driven Development with Cucumber
django Forms in a Web API World
BDD style Unit Testing
Using the latest Java Persistence API 2 Features - Tech Days 2010 India
A Deep Dive into the W3C WebDriver Specification
Karate DSL
2016 - Serverless Microservices on AWS with API Gateway and Lambda
Metaprogramming JavaScript
Refactoring
Introduction to testing in Rails
ExpertTalks Manchester September 2018
Ibm_interconnect_restapi_workshop
Cqrs api
Ad

Viewers also liked (7)

ODP
Acts As Most Popular
PDF
Nine at Mary Brickell Village brochure
PDF
Cache Money Talk: Practical Application
PDF
Paraiso Bay floor plans
ODP
2009 07 21: Nested Attributes
PDF
Axis Brickell Floor Plans
PDF
Faena House floor plans
Acts As Most Popular
Nine at Mary Brickell Village brochure
Cache Money Talk: Practical Application
Paraiso Bay floor plans
2009 07 21: Nested Attributes
Axis Brickell Floor Plans
Faena House floor plans
Ad

Similar to 2010-07-19_rails_tdd_week1 (20)

PPTX
TDD & BDD
PPTX
Beginners overview of automated testing with Rspec
PDF
Testing survival Guide
PDF
Test and Behaviour Driven Development (TDD/BDD)
ODP
Effective TDD - Less is more
PDF
Beyond Testing: Specs and Behavior Driven Development
PDF
Rethinking Testing
PDF
PPTX
An Introduction To Software Development - Test Driven Development, Part 1
PPTX
TeDevelopment Testing in Software Engineering
KEY
Testing Has Many Purposes
PDF
Software Quality and Test Strategies for Ruby and Rails Applications
KEY
TDD refresher
PDF
WTF is TDD
PDF
Introduction to-automated-testing
PDF
Introduction to Automated Testing
PDF
What CS Class Didn't Teach About Testing
PDF
Efficient Rails Test Driven Development (class 3) by Wolfram Arnold
PDF
PPTX
Understanding TDD - theory, practice, techniques and tips.
TDD & BDD
Beginners overview of automated testing with Rspec
Testing survival Guide
Test and Behaviour Driven Development (TDD/BDD)
Effective TDD - Less is more
Beyond Testing: Specs and Behavior Driven Development
Rethinking Testing
An Introduction To Software Development - Test Driven Development, Part 1
TeDevelopment Testing in Software Engineering
Testing Has Many Purposes
Software Quality and Test Strategies for Ruby and Rails Applications
TDD refresher
WTF is TDD
Introduction to-automated-testing
Introduction to Automated Testing
What CS Class Didn't Teach About Testing
Efficient Rails Test Driven Development (class 3) by Wolfram Arnold
Understanding TDD - theory, practice, techniques and tips.

Recently uploaded (20)

PPTX
Modernising the Digital Integration Hub
PDF
CloudStack 4.21: First Look Webinar slides
PDF
Improvisation in detection of pomegranate leaf disease using transfer learni...
PDF
A proposed approach for plagiarism detection in Myanmar Unicode text
PDF
Credit Without Borders: AI and Financial Inclusion in Bangladesh
PPTX
Final SEM Unit 1 for mit wpu at pune .pptx
PDF
Taming the Chaos: How to Turn Unstructured Data into Decisions
PDF
Architecture types and enterprise applications.pdf
PDF
sbt 2.0: go big (Scala Days 2025 edition)
PDF
Consumable AI The What, Why & How for Small Teams.pdf
PPTX
The various Industrial Revolutions .pptx
PPT
Geologic Time for studying geology for geologist
DOCX
search engine optimization ppt fir known well about this
PDF
How ambidextrous entrepreneurial leaders react to the artificial intelligence...
PDF
Produktkatalog für HOBO Datenlogger, Wetterstationen, Sensoren, Software und ...
PDF
A review of recent deep learning applications in wood surface defect identifi...
PDF
Hybrid horned lizard optimization algorithm-aquila optimizer for DC motor
PDF
Developing a website for English-speaking practice to English as a foreign la...
PPTX
Benefits of Physical activity for teenagers.pptx
PDF
How IoT Sensor Integration in 2025 is Transforming Industries Worldwide
Modernising the Digital Integration Hub
CloudStack 4.21: First Look Webinar slides
Improvisation in detection of pomegranate leaf disease using transfer learni...
A proposed approach for plagiarism detection in Myanmar Unicode text
Credit Without Borders: AI and Financial Inclusion in Bangladesh
Final SEM Unit 1 for mit wpu at pune .pptx
Taming the Chaos: How to Turn Unstructured Data into Decisions
Architecture types and enterprise applications.pdf
sbt 2.0: go big (Scala Days 2025 edition)
Consumable AI The What, Why & How for Small Teams.pdf
The various Industrial Revolutions .pptx
Geologic Time for studying geology for geologist
search engine optimization ppt fir known well about this
How ambidextrous entrepreneurial leaders react to the artificial intelligence...
Produktkatalog für HOBO Datenlogger, Wetterstationen, Sensoren, Software und ...
A review of recent deep learning applications in wood surface defect identifi...
Hybrid horned lizard optimization algorithm-aquila optimizer for DC motor
Developing a website for English-speaking practice to English as a foreign la...
Benefits of Physical activity for teenagers.pptx
How IoT Sensor Integration in 2025 is Transforming Industries Worldwide

2010-07-19_rails_tdd_week1

  • 1. Efficient Rails Test-Driven Development Wolfram Arnold www.rubyfocus.biz In collaboration with: Sarah Allen, BlazingCloud.net marakana.com
  • 2. Class Outline Week #1 The economics of testing Testing in layers, design patterns Toolbox: RSpec with Rails RSpec & Models Week #2 A culture of testing: Why TDD? How to TDD? Testing & Data Dependencies Toolbox: Fixtures, Factories, Mocks & Stubs
  • 3. Class Outline Week #3 Controller testing View, Helper, Routes Testing How much is enough? How much is too much? Week #4 Refactoring code & tests, custom matchers API Testing Remote data setup Cucumber for API testing & documentation
  • 4. Class Outline Week #5 Integration Testing—when and how? Toolbox: Cucumber, Selenium & Friends Page Object Pattern Week #6 TDD—what next? BDD, Agile Process, XP → VDD: Value-Driven Development Advanced/Special Requests
  • 5. What you can expect Presentation, Examples Answers to questions A range of material from current development practice Homework Fluidity & adaptability Fun
  • 6. It works best, when... Active participation Try something new Focus Team Effort Pairing Utilizing the resources in class: TA's, participants Discussions in public Class Q&A Mailing list
  • 8. Why “efficient” and “testing”? “Testing takes too much time.” “It's more efficient to test later.” “Testing is the responsibility of QA, not developers.” “It's not practical to test X.” Tests break when data changes. Tests break when design changes.
  • 9. The Role of Testing Development without tests... fails to empower developers to efficiently take responsibility for quality of the code delivered makes collaboration harder build narrow silos of expertise instills fear & resistance to change makes documentation a chore stops being efficient very soon
  • 10. TDD: Keeping cost of change low Cost per change without TDD with TDD Time
  • 11. Why? Non-TDD Accumulates “technical debt” unchecked Removal of technical debt carries risk The more technical debt, the higher the risk Existing technical debt attracts more technical debt Like compound interest People are most likely to do what others did before them To break the pattern heroic discipline & coordination required
  • 12. Testing in Layers Application, Browser UI Selenium RSpec Integration Test::Unit Integration Application, Server Cucumber, Webrat RSpec RSpec Views Helpers Views Helpers RSpec RSpec Test::Unit Functional Controller Routes Controller Routes RSpec Test::Unit Model Model
  • 13. Cost of Testing Layers Application, Browser UI Application, Server Views Helpers Controller Routes Model Cost
  • 14. Cost of Testing Relationship to data most Application, Browser UI removed Application, Server Views Helpers Controller Routes Model closest Cost
  • 15. Best ROI for Testing Layers Application, Browser UI Application, Server Views Helpers Controller Routes Model Impact/Line of Test Code
  • 16. TDD & Design Patterns Skinny Controller— ➢ Designed to move logic Fat Model from higher to lower DRY application layers named_scope ➢ Following design patterns makes testing Proxy Associations easier Validations ➢ Code written following ... TDD economics will naturally converge on these design patterns!
  • 17. Structure of Tests Setup Expected value Actual value Verification: actual == expected? Teardown
  • 18. Good Tests are... Compact Responsible for testing one concern only Fast DRY
  • 19. RSpec Verifications should respond_to should be_nil → works with any ? method (so-called “predicates”) should be_valid should_not be_nil; should_not be_valid lambda {...}.should change(), {}, .from().to(), .by() should eql, ==, equal
  • 20. RSpec Structure before, before(:each), before(:all) after, after(:each), after(:all) describe do...end, nested it do... end
  • 21. Let's do some coding Demo
  • 22. Models: What to test? Validation Rules Associations Any custom method Association Proxy Methods
  • 23. Let's do some coding Exercise, but wait...
  • 24. Test-First Teaching Pioneered by Sarah Allen Instructor writes tests Students write code What about writing tests?
  • 25. Behavior-First Teaching Instructor specifies desired behavior in plain English like a user story Students write tests Students write code to make tests pass
  • 26. Story Exercise #1 A Person object must have a first and last name. A Person object can construct a full name from the first and last name. A Person object has an optional middle name. A Person object returns a full name including, if present, the middle name.
  • 27. RSpec ==, eql, equal obj.should == 5 5 == 5 obj.should eql(5) 5.eql 5 obj.should equal(5) 5.equal 5 Object Equality vs. Identity Use == eql, == compare values Unless you know you need something else equal, === compare objects, classes Warning! Do not use != with RSpec. Use should_not instead.
  • 28. RSpec should change lambda { Person.create }.should change(Person, :count).by(1) lambda { @bob.addresses.create(:street => “...”) }.should change(@bob.addresses, :count).by(1) nd Warning: The 2 example is incorrect!
  • 29. RSpec should change lambda { # code that causes a change }.should change(object, :method).by(difference) or should change(object, :method).from(initial).to(final) The object typically is a class, if not, be wary of reload!
  • 30. should change with block lambda { # code that causes a change }.should change { expression }.by(difference) or should change { expression }.from(initial).to(final)
  • 31. better with block lambda { @bob.addresses.create(:street => “...”) }.should change { @bob.addresses(true).count }.by(1)
  • 32. Homework A Person should save correctly. A Person can have many Addresses. A Person's Address must have a street, city and zip. A Person's Address can have an optional country. If the country is left blank, it should default to “USA” prior to saving.
  • 33. BizConf Aug 4-6, 2010 Amelia Island, FL Discount code: WOLF Rails & Web App Professionals, Entrepreneurs, for 43% off Consultants http://bizconf.org? Small group coupon=WOLF Network with Who's Who Organized by Obie Fernandez of Hashrocket Highlight: David Allen