SlideShare una empresa de Scribd logo
CURSO DE TESTING OSL
        12 – 16 DE ABRIL 2010



            Test Driven Development – TDD
           (Desarrollo dirigido por pruebas)

Alberto Perdomo

Web:       http://albertoperdomo.net
Email:     alberto.perdomo@aentos.es
Twitter:   @albertoperdomo             http://www.aentos.com
DESARROLLO WEB ÁGIL
 FUNCIONALIDAD n        FUNCIONALIDAD n+1



      DISEÑO                 DISEÑO




  IMPLEMENTACIÓN         IMPLEMENTACIÓN




PRUEBAS / VALIDACIÓN   PRUEBAS / VALIDACIÓN



    DESPLIEGUE             DESPLIEGUE
TDD: EL ORÍGEN

→ El test-driven development es un concepto estrechamente
relacionado con el extreme programming, que emerge en
1999.


→ Recientemente ha obtenido atención como técnica
individual.


→ Creador: Kent Beck, uno de los frmantes originales del
Manifesto Ágil
TDD: EL CONCEPTO


  PRUEBA
 PRIMERO,

IMPLEMENTA
  DESPUÉS
PROBLEMAS DE ESCRIBIR LAS
  PRUEBAS DESPUÉS DEL
       CÓDIGO I

→ Sabemos cómo está escrito el código y por lo tanto estamos
viciados a la hora de probarlo


→ Pensamos en probar cómo está implementado y no en
probar cómo debería funcionar desde la perspectiva del
usuario
EJEMPLO
Implementación

class User < ActiveRecord::Base

  def full_name
    first_name + " " + last_name
  end                                         Para una instancia del modelo User
                                              con atributos frst_name “Alberto”
                                              y last_name “Perdomo” el método
end

                                              full_name debe devolver “Alberto
                                              Perdomo”



Test

  def test_full_name
    person = User.new(:first_name => "Alberto", :last_name => "Perdomo")
    assert_equal "Alberto Perdomo", user.full_name
  end
PROBLEMAS DE ESCRIBIR LAS
  PRUEBAS DESPUÉS DEL
       CÓDIGO II

Estamos viciados con la implementación


  → Pruebas inadecuadas


  → Pruebas que no funcionan


  → Pruebas frágiles basadas en la implementación, no en el
  comportamiento
EJEMPLO
Implementación

class User < ActiveRecord::Base

  def full_name
    first_name + " " + last_name
  end

end                                           El test nunca dará error aunque el
                                              método deje de funcionar
                                              correctamente




Test

  def test_full_name
    person = User.new(:first_name => "Alberto", :last_name => "Perdomo")
    #assert_equal "Alberto Perdomo", user.full_name
  end
DESARROLLO TDD
 FUNCIONALIDAD n        FUNCIONALIDAD n+1



      DISEÑO                 DISEÑO




PRUEBAS / VALIDACIÓN   PRUEBAS / VALIDACIÓN




  IMPLEMENTACIÓN         IMPLEMENTACIÓN



    DESPLIEGUE             DESPLIEGUE
TDD: PASO 1

Escribir un test automatizado que defna la mejora o nueva
funcionalidad


→ Esta prueba debe fallar, ya que aún no hemos
implementado el código


→ FAILURE
EJEMPLO PASO 1: ESCRIBIR
        PRUEBA

 def test_full_name_without_first_name
   person = User.new(:first_name => nil, :last_name => "Perdomo")
   assert_equal "Perdomo", user.full_name
 end

 def test_full_name_without_last_name
   person = User.new(:first_name => "Alberto", :last_name => nil)
   assert_equal "Alberto", user.full_name
 end

 def test_full_name
   person = User.new(:first_name => "Alberto", :last_name => "Perdomo")
   assert_equal "Alberto Perdomo", user.full_name
 end

 def test_full_name_anonymous
   person = User.new(:first_name => nil, :last_name => nil)
   assert_equal "", user.full_name
 end
TDD: PASO 2


Implementar el código para satisfacer la prueba


→ Al fnalizar este paso la prueba debe pasar con éxito


→ OK
EJEMPLO PASO 2: IMPLEMENTAR

       class User < ActiveRecord::Base

         def full_name
           if first.name.nil? && last.name.nil?
             ""
           elsif first.name.nil?
             last_name
           elsif last.name_nil?
             first_name
           else
             first_name + " " + last_name
           end
         end

       end
TDD: PASO 3


Refactorizamos el código manteniendo el comportamiento


Al fnal de este paso la prueba debe seguir pasando con éxito


→ OK
EJEMPLO PASO 3:
 REFACTORIZAR

 class User < ActiveRecord::Base

   def full_name
     [first_name, last_name].join(" ").strip
   end

 end
EL MANTRA DEL TDD



RED
GREEN
REFACTOR
¿PREGUNTAS?

Más contenido relacionado

PDF
Curso TDD Ruby on Rails #04: Factorías de objetos
PDF
Curso TDD Ruby on Rails #03: Tests unitarios
PDF
Curso TDD Ruby on Rails #01: Introducción al testing
PPTX
Unidad 5: Excepciones Ejercicio 2
DOCX
Comandos java
PPTX
Unidad 5: Excepciones Ejercicio 3
PDF
Palabras reservadas en java y tipos de datos en java
Curso TDD Ruby on Rails #04: Factorías de objetos
Curso TDD Ruby on Rails #03: Tests unitarios
Curso TDD Ruby on Rails #01: Introducción al testing
Unidad 5: Excepciones Ejercicio 2
Comandos java
Unidad 5: Excepciones Ejercicio 3
Palabras reservadas en java y tipos de datos en java

La actualidad más candente (19)

PDF
Taller de PHP Básico
PPT
Unit Testing - GTUG
DOCX
Documento Margarita
DOCX
Comandos de Java
DOCX
Comandos Java
PDF
Ocho cosas que debes saber de JavaScript
PPT
Rompiendo dependencias contenidas en ensamblados .NET mediante la refactoriza...
ODP
Toi Tdd 20080409
PDF
Semana 1 Estructuras de Datos en Java
PDF
¿Cómo mantener tu javascript?: Buenas prácticas
PPSX
Estructuras de control en js
DOCX
Entidades
PPTX
Constructores
 
PPS
Clase n°2 3-4 java
PPTX
Clase 2 3 estructuras de control
PDF
Semana 6 Módulos en Python Entrega 2
PPT
IntroduccióN A Visual C
PDF
Vocabulario java isabella o'byrne paz 11 2
PPT
Best Practices
Taller de PHP Básico
Unit Testing - GTUG
Documento Margarita
Comandos de Java
Comandos Java
Ocho cosas que debes saber de JavaScript
Rompiendo dependencias contenidas en ensamblados .NET mediante la refactoriza...
Toi Tdd 20080409
Semana 1 Estructuras de Datos en Java
¿Cómo mantener tu javascript?: Buenas prácticas
Estructuras de control en js
Entidades
Constructores
 
Clase n°2 3-4 java
Clase 2 3 estructuras de control
Semana 6 Módulos en Python Entrega 2
IntroduccióN A Visual C
Vocabulario java isabella o'byrne paz 11 2
Best Practices
Publicidad

Similar a Curso TDD Ruby on Rails #02: Test Driven Development (20)

PPTX
TDD Workshop
PPSX
7iSF-4 test driver development
PPTX
Buenas practicas desarrollando software
PPT
Seminario de Test Development Driven
PDF
Introducción a TDD
PPTX
TDD (Test-Driven Development)
PDF
Agile university day - Un día en un equipo ágil de desarrollo móvil
ODP
Cómo hacer Test Driven Development
PDF
Apuntes #XPweek
PDF
Metodologías Aágiles: TDD (Test Driven development)
PPTX
Unidad ii. tdd
PPTX
PPTX
Artalde Tdd intro
PDF
Artesania de Software y TDD
PPTX
Introducción a tdd
PPT
Tdd on the rocks
PPTX
Artesania de Software y TDD
TDD Workshop
7iSF-4 test driver development
Buenas practicas desarrollando software
Seminario de Test Development Driven
Introducción a TDD
TDD (Test-Driven Development)
Agile university day - Un día en un equipo ágil de desarrollo móvil
Cómo hacer Test Driven Development
Apuntes #XPweek
Metodologías Aágiles: TDD (Test Driven development)
Unidad ii. tdd
Artalde Tdd intro
Artesania de Software y TDD
Introducción a tdd
Tdd on the rocks
Artesania de Software y TDD
Publicidad

Más de Alberto Perdomo (11)

PDF
Primeros pasos con la base de datos de grafos Neo4j
PDF
Leveraging relations at scale with Neo4j
PDF
Squire: A polyglot application combining Neo4j, MongoDB, Ruby and Scala @ FOS...
PDF
Rails for Mobile Devices @ Conferencia Rails 2011
PDF
Boost your productivity!: Productivity tips for rails developers - Lightning ...
PDF
Strangers In The Night: Ruby, Rack y Sinatra - Herramientas potentes para con...
PDF
Curso TDD Ruby on Rails #08: Buenas prácticas
PDF
Curso TDD Ruby on Rails #02: Test Driven Development
PDF
Curso TDD Ruby on Rails #06: Mocks y stubs
PDF
Curso TDD Ruby on Rails #05: Shoulda
PDF
Plugins de autenticación en Rails - Lightning talk Las Palmas On Rails 09/02/...
Primeros pasos con la base de datos de grafos Neo4j
Leveraging relations at scale with Neo4j
Squire: A polyglot application combining Neo4j, MongoDB, Ruby and Scala @ FOS...
Rails for Mobile Devices @ Conferencia Rails 2011
Boost your productivity!: Productivity tips for rails developers - Lightning ...
Strangers In The Night: Ruby, Rack y Sinatra - Herramientas potentes para con...
Curso TDD Ruby on Rails #08: Buenas prácticas
Curso TDD Ruby on Rails #02: Test Driven Development
Curso TDD Ruby on Rails #06: Mocks y stubs
Curso TDD Ruby on Rails #05: Shoulda
Plugins de autenticación en Rails - Lightning talk Las Palmas On Rails 09/02/...

Último (20)

PPTX
ANCASH-CRITERIOS DE EVALUACIÓN-FORMA-10-10 (2).pptx
PPTX
Propuesta BKP servidores con Acronis1.pptx
PPT
Que son las redes de computadores y sus partes
PPTX
RAP02 - TECNICO SISTEMAS TELEINFORMATICOS.pptx
PPTX
Acronis Cyber Protect Cloud para Ciber Proteccion y Ciber Seguridad LATAM - A...
PPTX
Sesion 1 de microsoft power point - Clase 1
PDF
Estrategia de apoyo tecnología grado 9-3
PPTX
Presentación PASANTIAS AuditorioOO..pptx
PDF
taller de informática - LEY DE OHM
PDF
Instrucciones simples, respuestas poderosas. La fórmula del prompt perfecto.
PDF
Diapositiva proyecto de vida, materia catedra
PDF
CyberOps Associate - Cisco Networking Academy
PPTX
IA de Cine - Como MuleSoft y los Agentes estan redefiniendo la realidad
DOCX
Zarate Quispe Alex aldayir aplicaciones de internet .docx
PPTX
Presentación de Redes de Datos modelo osi
PPTX
sa-cs-82-powerpoint-hardware-y-software_ver_4.pptx
PDF
MANUAL TECNOLOGÍA SER MINISTERIO EDUCACIÓN
PPTX
REDES INFORMATICAS REDES INFORMATICAS.pptx
PDF
Liceo departamental MICRO BIT (1) 2.pdfbbbnn
PDF
MÓDULO DE CALOR DE GRADO DE MEDIO DE FORMACIÓN PROFESIONAL
ANCASH-CRITERIOS DE EVALUACIÓN-FORMA-10-10 (2).pptx
Propuesta BKP servidores con Acronis1.pptx
Que son las redes de computadores y sus partes
RAP02 - TECNICO SISTEMAS TELEINFORMATICOS.pptx
Acronis Cyber Protect Cloud para Ciber Proteccion y Ciber Seguridad LATAM - A...
Sesion 1 de microsoft power point - Clase 1
Estrategia de apoyo tecnología grado 9-3
Presentación PASANTIAS AuditorioOO..pptx
taller de informática - LEY DE OHM
Instrucciones simples, respuestas poderosas. La fórmula del prompt perfecto.
Diapositiva proyecto de vida, materia catedra
CyberOps Associate - Cisco Networking Academy
IA de Cine - Como MuleSoft y los Agentes estan redefiniendo la realidad
Zarate Quispe Alex aldayir aplicaciones de internet .docx
Presentación de Redes de Datos modelo osi
sa-cs-82-powerpoint-hardware-y-software_ver_4.pptx
MANUAL TECNOLOGÍA SER MINISTERIO EDUCACIÓN
REDES INFORMATICAS REDES INFORMATICAS.pptx
Liceo departamental MICRO BIT (1) 2.pdfbbbnn
MÓDULO DE CALOR DE GRADO DE MEDIO DE FORMACIÓN PROFESIONAL

Curso TDD Ruby on Rails #02: Test Driven Development

  • 1. CURSO DE TESTING OSL 12 – 16 DE ABRIL 2010 Test Driven Development – TDD (Desarrollo dirigido por pruebas) Alberto Perdomo Web: http://albertoperdomo.net Email: alberto.perdomo@aentos.es Twitter: @albertoperdomo http://www.aentos.com
  • 2. DESARROLLO WEB ÁGIL FUNCIONALIDAD n FUNCIONALIDAD n+1 DISEÑO DISEÑO IMPLEMENTACIÓN IMPLEMENTACIÓN PRUEBAS / VALIDACIÓN PRUEBAS / VALIDACIÓN DESPLIEGUE DESPLIEGUE
  • 3. TDD: EL ORÍGEN → El test-driven development es un concepto estrechamente relacionado con el extreme programming, que emerge en 1999. → Recientemente ha obtenido atención como técnica individual. → Creador: Kent Beck, uno de los frmantes originales del Manifesto Ágil
  • 4. TDD: EL CONCEPTO PRUEBA PRIMERO, IMPLEMENTA DESPUÉS
  • 5. PROBLEMAS DE ESCRIBIR LAS PRUEBAS DESPUÉS DEL CÓDIGO I → Sabemos cómo está escrito el código y por lo tanto estamos viciados a la hora de probarlo → Pensamos en probar cómo está implementado y no en probar cómo debería funcionar desde la perspectiva del usuario
  • 6. EJEMPLO Implementación class User < ActiveRecord::Base def full_name first_name + " " + last_name end Para una instancia del modelo User con atributos frst_name “Alberto” y last_name “Perdomo” el método end full_name debe devolver “Alberto Perdomo” Test def test_full_name person = User.new(:first_name => "Alberto", :last_name => "Perdomo") assert_equal "Alberto Perdomo", user.full_name end
  • 7. PROBLEMAS DE ESCRIBIR LAS PRUEBAS DESPUÉS DEL CÓDIGO II Estamos viciados con la implementación → Pruebas inadecuadas → Pruebas que no funcionan → Pruebas frágiles basadas en la implementación, no en el comportamiento
  • 8. EJEMPLO Implementación class User < ActiveRecord::Base def full_name first_name + " " + last_name end end El test nunca dará error aunque el método deje de funcionar correctamente Test def test_full_name person = User.new(:first_name => "Alberto", :last_name => "Perdomo") #assert_equal "Alberto Perdomo", user.full_name end
  • 9. DESARROLLO TDD FUNCIONALIDAD n FUNCIONALIDAD n+1 DISEÑO DISEÑO PRUEBAS / VALIDACIÓN PRUEBAS / VALIDACIÓN IMPLEMENTACIÓN IMPLEMENTACIÓN DESPLIEGUE DESPLIEGUE
  • 10. TDD: PASO 1 Escribir un test automatizado que defna la mejora o nueva funcionalidad → Esta prueba debe fallar, ya que aún no hemos implementado el código → FAILURE
  • 11. EJEMPLO PASO 1: ESCRIBIR PRUEBA def test_full_name_without_first_name person = User.new(:first_name => nil, :last_name => "Perdomo") assert_equal "Perdomo", user.full_name end def test_full_name_without_last_name person = User.new(:first_name => "Alberto", :last_name => nil) assert_equal "Alberto", user.full_name end def test_full_name person = User.new(:first_name => "Alberto", :last_name => "Perdomo") assert_equal "Alberto Perdomo", user.full_name end def test_full_name_anonymous person = User.new(:first_name => nil, :last_name => nil) assert_equal "", user.full_name end
  • 12. TDD: PASO 2 Implementar el código para satisfacer la prueba → Al fnalizar este paso la prueba debe pasar con éxito → OK
  • 13. EJEMPLO PASO 2: IMPLEMENTAR class User < ActiveRecord::Base def full_name if first.name.nil? && last.name.nil? "" elsif first.name.nil? last_name elsif last.name_nil? first_name else first_name + " " + last_name end end end
  • 14. TDD: PASO 3 Refactorizamos el código manteniendo el comportamiento Al fnal de este paso la prueba debe seguir pasando con éxito → OK
  • 15. EJEMPLO PASO 3: REFACTORIZAR class User < ActiveRecord::Base def full_name [first_name, last_name].join(" ").strip end end
  • 16. EL MANTRA DEL TDD RED GREEN REFACTOR