SlideShare a Scribd company logo
1 of 31
Download to read offline
Efficient Rails Test-DrivenEfficient Rails Test-Driven
Development — Week 4Development — Week 4
Wolfram ArnoldWolfram Arnold
www.rubyfocus.bizwww.rubyfocus.biz
In collaboration with:In collaboration with:
Sarah Allen, BlazingCloud.netSarah Allen, BlazingCloud.net
marakana.commarakana.com
ControllersControllers
ControllersControllers
Controllers are pass-through entities
Mostly boilerplate—biz logic belongs in the model
Controllers are “dumb” or “skinny”
They follow a run-of-the mill pattern:
the Controller Formula
Controller RESTful ActionsController RESTful Actions
Display methods (“Read”)
GET: index, show, new, edit
Update method
PUT
Create method
POST
Delete method
DELETE
REST?REST?
Representational State Transfer
All resource-based applications & API's need to
do similar things, namely:
create, read, update, delete
It's a convention:
no configuration, no ceremony
superior to CORBA, SOAP, etc.
RESTful rsources in RailsRESTful rsources in Rails
map.resources :people (in config/routes.rb)
people_path, people_url “named route methods”
GET /people → “index” action
POST /people → “create” action
new_person_path, new_person_url
GET /people/new → “new” action
edit_person_path, edit_person_url
GET /people/:id/edit → “edit” action with ID
person_path, person_url
GET /people/:id → “show” action with ID
PUT /people/:id → “update” action with ID
DELETE /people/:id → “destroy” action with ID
Reads Test PatternReads Test Pattern
Make request (with id of record if a single record)
Check Rendering
correct template
redirect
status code
content type (HTML, JSON, XML,...)
Verify Variable Assignments
required by view
Read FormulaRead Formula
Find data, based on parameters
Assign variables
Render
How much test is too much?How much test is too much?
Test anything where the code deviates from
defaults, e.g. redirect vs. straight up render
These tests are not strictly necessary:
response.should be_success
response.should render_template('new')
Test anything required for the application to
proceed without error
Speficially variable assignments
Do test error handling code!
form_for's automagic powersform_for's automagic powers
form_for @person do |f| ... end
When @person is new
→ <form action=”people” method=”post”>
→ PeopleController#create
→ uses people_path method to generate URL
When @person exists already
→ <form action=”people” method=”put”>
→ PeopleController#update
→ uses person_path method to generate URL
Create/Update Test PatternCreate/Update Test Pattern
Make request with form fields to be created/upd'd
Verify Variable Assignments
Verify Check Success
Rendering
Verify Failure/Error Case
Rendering
Variables
Verify HTTP Verb protection
Create/Update FormulaCreate/Update Formula
Update: Find record from parameters
Create: Instantiate new model object
Assign form fields parameters to model object
This should be a single line
It is a pattern, the “Controller Formula”
Save
Handle success—typically a redirect
Handle failure—typically a render
Destroy Test PatternDestroy Test Pattern
Make request with id of record to be destroyed
Rendering
Typically no need to check for success or failure
Invalid item referenced → Same behavior as read
Database deletion failed → System not user error
Destroy FormulaDestroy Formula
Find record from parameters
Destroy
Redirect
How much is enough?How much is enough?
Notice: No view testing so far.
Emphasize behavior over display.
Check that the application handles errors
correctly
Test views only for things that could go wrong
badly
incorrect form URL
incorrect names on complicated forms, because they
impact parameter representation
View TestingView Testing
RSpec controllers do not render views (by
default)
Test form urls, any logic and input names
Understand CSS selector syntax
View test requires set up of variables
another reason why there should only be very few
variables between controller and view
A note on RJSA note on RJS
RJS lets you render a JS response using “RJS”
Built on Prototype JS framework
Hard to test
Largely superseded by
RSpec tested controllers responding in JSON
JS tests mocking the server response
jQuery's Ajax library very helpful
RSpec Scaffold & MocksRSpec Scaffold & Mocks
RSpec Scaffold mocks models
Their philosophy is outside-in development
I'm not a fan of this because:
It causes gaps in coverage
Mocks need to be maintained
Outside-in remains unproven beyond textbook
examples
When taken to the extreme, it can become un-Agile
by over-specifying the application
NestedNested
AttributesAttributes
One Form—Multiple ModelsOne Form—Multiple Models
DB schema should not limit view/form layout
View/form layout should not impose DB schema
A single form to manipulate associated rows of
multiple tables.
→ Nested Attributes
View & Model CollaborationView & Model Collaboration
Model:
accepts_nested_attributes_for
View:
form_for
fields_for
Controller is unaware! Strictly pass-through
Person.new(params[:person])
accepts_nested_attributes_foraccepts_nested_attributes_for
class Person < ActiveRecord::Base
has_many :addresses
accepts_nested_attributes_for :addresses
end
Person.create(:first_name => “Joe”,
:last_name => “Smith”,
:addresses_attributes => [ {
:street => “123 Main,
:city => “San Francisco”,
:zip => “94103”,
:state => “CA” } ]
Nested Attributes New & OldNested Attributes New & Old
A new record is recognized by absence of an id:
:address_attributes => [ {:city => “SF”, :zip =>
“12345”, :street => “123 Main”, :state => “CA”} ]
An existing record is recognized by presence of
an id:
:address_attributes => [ { :id => “5”,
:city => “SF”, :zip => “12345”,
:street => “123 Main”, :state => “CA”} ]
Nested Attr's Singular & PluralNested Attr's Singular & Plural
has_many :addresses
:addresses_attributes => [ { record1 },
{ record2 } ]
has_one :address_of_record
:address_attributes => { record }
Nested Attributes ParametersNested Attributes Parameters
:allow_destroy => true
removes an existing record with _destroy => '1'
default is false
:reject_if => :method or Proc.new { |attrs| ... }
suppresses creation or updating when false
can pass :all_blank to skip records with all blank attr's
:limit => 5
limits numbers of records creatable from nested attr's
:update_only
prevents multiple records for 1-on-1 associations
Textbook Outside-In BDDTextbook Outside-In BDD
Yes...
Helps to lay out model requirements via mocks
But...
Mocks get out of sync
A lot more work for not very much improved coverage
Best place is exploratory testing
Does nothing to encourage fat model/skinny
controller paradigm
Knowledge of advanced model features still key
Value-Driven Outside-In BDDValue-Driven Outside-In BDD
Write controller tests first
Make them pending while fleshing out model
Implement model logic with
nested_scopes
associations, with rich options & proxy methods
accepts_nested_attributes_for
Resume controller test
Add views
Exploratory Cucumber/Selenium test
to avoid test gap between view & controller
HomeworkHomework
HomeworkHomework
As a person, I can update my name along with an
addresses on the same form.
Extra credit:
Using JavaScript, create an “add one” link on the
new form that replicates the address sub-form,
to permit entering more than one address.
Same for a delete link.
Reuse the above mechanism for the edit form.
Recommended ReadingRecommended Reading
http://railscasts.com/episodes/196-nested-model-form-part-1
http://asciicasts.com/episodes/196-nested-model-form-part-1
http://railscasts.com/episodes/197-nested-model-form-part-2
http://asciicasts.com/episodes/197-nested-model-form-part-2
http://docs.jquery.com/Main_Page
http://activescaffold.com/
Nested Attributes API Docs: http://bit.ly/7cnt0
Form for (with nest'd attr's) API Docs:
http://bit.ly/9DAscq
My presentation on nested attributes: http://blip.tv/file/3957941
RSpec book chapters 1.5, 10, 11 (on BDD)
RSpec book chapter 20 (outside-in development)
Flickr Photo Attribute CreditFlickr Photo Attribute Credit
Matroshka nested dolls
http://www.flickr.com/photos/shereen84/2511071028/sizes/l/
Notebook with pencil
http://www.flickr.com/photos/tomsaint/2987926396/sizes/l/
Control Panel
http://www.flickr.com/photos/900hp/3961052527/sizes/l/

More Related Content

What's hot

MVC & SQL_In_1_Hour
MVC & SQL_In_1_HourMVC & SQL_In_1_Hour
MVC & SQL_In_1_HourDilip Patel
 
Kiss PageObjects [01-2017]
Kiss PageObjects [01-2017]Kiss PageObjects [01-2017]
Kiss PageObjects [01-2017]Iakiv Kramarenko
 
Handlebars and Require.js
Handlebars and Require.jsHandlebars and Require.js
Handlebars and Require.jsIvano Malavolta
 
Introduction to Selenium and Ruby
Introduction to Selenium and RubyIntroduction to Selenium and Ruby
Introduction to Selenium and RubyYnon Perek
 
In memory OLAP engine
In memory OLAP engineIn memory OLAP engine
In memory OLAP engineWO Community
 
Two scoops of django 1.6 - Ch7, Ch8
Two scoops of django 1.6  - Ch7, Ch8Two scoops of django 1.6  - Ch7, Ch8
Two scoops of django 1.6 - Ch7, Ch8flywindy
 
Coding with style: The Scalastyle style checker
Coding with style: The Scalastyle style checkerCoding with style: The Scalastyle style checker
Coding with style: The Scalastyle style checkerMatthew Farwell
 
Introduction to Sightly
Introduction to SightlyIntroduction to Sightly
Introduction to SightlyAnkit Gubrani
 
Jasig Rubyon Rails
Jasig Rubyon RailsJasig Rubyon Rails
Jasig Rubyon RailsPaul Pajo
 
An Introduction to Ruby on Rails
An Introduction to Ruby on RailsAn Introduction to Ruby on Rails
An Introduction to Ruby on RailsJoe Fiorini
 
Write Selenide in Python 15 min
Write Selenide in Python 15 minWrite Selenide in Python 15 min
Write Selenide in Python 15 minIakiv Kramarenko
 
25 Real Life Tips In Ruby on Rails Development
25 Real Life Tips In Ruby on Rails Development25 Real Life Tips In Ruby on Rails Development
25 Real Life Tips In Ruby on Rails DevelopmentBelighted
 
Testing mit Codeception: Full-stack testing PHP framework
Testing mit Codeception: Full-stack testing PHP frameworkTesting mit Codeception: Full-stack testing PHP framework
Testing mit Codeception: Full-stack testing PHP frameworkSusannSgorzaly
 
Unit Testing JavaScript Applications
Unit Testing JavaScript ApplicationsUnit Testing JavaScript Applications
Unit Testing JavaScript ApplicationsYnon Perek
 
D2W Stateful Controllers
D2W Stateful ControllersD2W Stateful Controllers
D2W Stateful ControllersWO Community
 

What's hot (20)

MVC & SQL_In_1_Hour
MVC & SQL_In_1_HourMVC & SQL_In_1_Hour
MVC & SQL_In_1_Hour
 
Kiss PageObjects [01-2017]
Kiss PageObjects [01-2017]Kiss PageObjects [01-2017]
Kiss PageObjects [01-2017]
 
Selenium bootcamp slides
Selenium bootcamp slides   Selenium bootcamp slides
Selenium bootcamp slides
 
Handlebars and Require.js
Handlebars and Require.jsHandlebars and Require.js
Handlebars and Require.js
 
Introduction to Selenium and Ruby
Introduction to Selenium and RubyIntroduction to Selenium and Ruby
Introduction to Selenium and Ruby
 
In memory OLAP engine
In memory OLAP engineIn memory OLAP engine
In memory OLAP engine
 
Two scoops of django 1.6 - Ch7, Ch8
Two scoops of django 1.6  - Ch7, Ch8Two scoops of django 1.6  - Ch7, Ch8
Two scoops of django 1.6 - Ch7, Ch8
 
Coding with style: The Scalastyle style checker
Coding with style: The Scalastyle style checkerCoding with style: The Scalastyle style checker
Coding with style: The Scalastyle style checker
 
Wt unit 5 client &amp; server side framework
Wt unit 5 client &amp; server side frameworkWt unit 5 client &amp; server side framework
Wt unit 5 client &amp; server side framework
 
Introduction to Sightly
Introduction to SightlyIntroduction to Sightly
Introduction to Sightly
 
Flask restless
Flask restlessFlask restless
Flask restless
 
Jasig Rubyon Rails
Jasig Rubyon RailsJasig Rubyon Rails
Jasig Rubyon Rails
 
An Introduction to Ruby on Rails
An Introduction to Ruby on RailsAn Introduction to Ruby on Rails
An Introduction to Ruby on Rails
 
Write Selenide in Python 15 min
Write Selenide in Python 15 minWrite Selenide in Python 15 min
Write Selenide in Python 15 min
 
Life outside WO
Life outside WOLife outside WO
Life outside WO
 
25 Real Life Tips In Ruby on Rails Development
25 Real Life Tips In Ruby on Rails Development25 Real Life Tips In Ruby on Rails Development
25 Real Life Tips In Ruby on Rails Development
 
Testing mit Codeception: Full-stack testing PHP framework
Testing mit Codeception: Full-stack testing PHP frameworkTesting mit Codeception: Full-stack testing PHP framework
Testing mit Codeception: Full-stack testing PHP framework
 
Unit Testing JavaScript Applications
Unit Testing JavaScript ApplicationsUnit Testing JavaScript Applications
Unit Testing JavaScript Applications
 
D2W Stateful Controllers
D2W Stateful ControllersD2W Stateful Controllers
D2W Stateful Controllers
 
Ruby On Rails
Ruby On RailsRuby On Rails
Ruby On Rails
 

Similar to Efficient Rails Test Driven Development (class 4) by Wolfram Arnold

2011-02-03 LA RubyConf Rails3 TDD Workshop
2011-02-03 LA RubyConf Rails3 TDD Workshop2011-02-03 LA RubyConf Rails3 TDD Workshop
2011-02-03 LA RubyConf Rails3 TDD WorkshopWolfram Arnold
 
Practical catalyst
Practical catalystPractical catalyst
Practical catalystdwm042
 
AEM Sightly Deep Dive
AEM Sightly Deep DiveAEM Sightly Deep Dive
AEM Sightly Deep DiveGabriel Walt
 
Introduction to JavaScript for APEX Developers - Module 1: JavaScript Basics
Introduction to JavaScript for APEX Developers - Module 1: JavaScript BasicsIntroduction to JavaScript for APEX Developers - Module 1: JavaScript Basics
Introduction to JavaScript for APEX Developers - Module 1: JavaScript BasicsDaniel McGhan
 
The Why and What of Pattern Lab
The Why and What of Pattern LabThe Why and What of Pattern Lab
The Why and What of Pattern LabDave Olsen
 
2010-07-19_rails_tdd_week1
2010-07-19_rails_tdd_week12010-07-19_rails_tdd_week1
2010-07-19_rails_tdd_week1Wolfram Arnold
 
Software Testing & PHPSpec
Software Testing & PHPSpecSoftware Testing & PHPSpec
Software Testing & PHPSpecDarren Craig
 
RubyOnRails-Cheatsheet-BlaineKendall
RubyOnRails-Cheatsheet-BlaineKendallRubyOnRails-Cheatsheet-BlaineKendall
RubyOnRails-Cheatsheet-BlaineKendalltutorialsruby
 
RubyOnRails-Cheatsheet-BlaineKendall
RubyOnRails-Cheatsheet-BlaineKendallRubyOnRails-Cheatsheet-BlaineKendall
RubyOnRails-Cheatsheet-BlaineKendalltutorialsruby
 
RSpec and Rails
RSpec and RailsRSpec and Rails
RSpec and RailsAlan Hecht
 
Ruby/Rails
Ruby/RailsRuby/Rails
Ruby/Railsrstankov
 
Random Ruby Tips - Ruby Meetup 27 Jun 2018
Random Ruby Tips - Ruby Meetup 27 Jun 2018Random Ruby Tips - Ruby Meetup 27 Jun 2018
Random Ruby Tips - Ruby Meetup 27 Jun 2018Kenneth Teh
 
td_mxc_rubyrails_shin
td_mxc_rubyrails_shintd_mxc_rubyrails_shin
td_mxc_rubyrails_shintutorialsruby
 
td_mxc_rubyrails_shin
td_mxc_rubyrails_shintd_mxc_rubyrails_shin
td_mxc_rubyrails_shintutorialsruby
 
MidwestPHP 2016 - Adventures in Laravel 5
MidwestPHP 2016 - Adventures in Laravel 5 MidwestPHP 2016 - Adventures in Laravel 5
MidwestPHP 2016 - Adventures in Laravel 5 Joe Ferguson
 
AngularJS Beginner Day One
AngularJS Beginner Day OneAngularJS Beginner Day One
AngularJS Beginner Day OneTroy Miles
 

Similar to Efficient Rails Test Driven Development (class 4) by Wolfram Arnold (20)

2011-02-03 LA RubyConf Rails3 TDD Workshop
2011-02-03 LA RubyConf Rails3 TDD Workshop2011-02-03 LA RubyConf Rails3 TDD Workshop
2011-02-03 LA RubyConf Rails3 TDD Workshop
 
Ruby On Rails
Ruby On RailsRuby On Rails
Ruby On Rails
 
Practical catalyst
Practical catalystPractical catalyst
Practical catalyst
 
AEM Sightly Deep Dive
AEM Sightly Deep DiveAEM Sightly Deep Dive
AEM Sightly Deep Dive
 
Introduction to JavaScript for APEX Developers - Module 1: JavaScript Basics
Introduction to JavaScript for APEX Developers - Module 1: JavaScript BasicsIntroduction to JavaScript for APEX Developers - Module 1: JavaScript Basics
Introduction to JavaScript for APEX Developers - Module 1: JavaScript Basics
 
The Why and What of Pattern Lab
The Why and What of Pattern LabThe Why and What of Pattern Lab
The Why and What of Pattern Lab
 
2010-07-19_rails_tdd_week1
2010-07-19_rails_tdd_week12010-07-19_rails_tdd_week1
2010-07-19_rails_tdd_week1
 
Software Testing & PHPSpec
Software Testing & PHPSpecSoftware Testing & PHPSpec
Software Testing & PHPSpec
 
RubyOnRails-Cheatsheet-BlaineKendall
RubyOnRails-Cheatsheet-BlaineKendallRubyOnRails-Cheatsheet-BlaineKendall
RubyOnRails-Cheatsheet-BlaineKendall
 
RubyOnRails-Cheatsheet-BlaineKendall
RubyOnRails-Cheatsheet-BlaineKendallRubyOnRails-Cheatsheet-BlaineKendall
RubyOnRails-Cheatsheet-BlaineKendall
 
RSpec and Rails
RSpec and RailsRSpec and Rails
RSpec and Rails
 
Ruby/Rails
Ruby/RailsRuby/Rails
Ruby/Rails
 
Random Ruby Tips - Ruby Meetup 27 Jun 2018
Random Ruby Tips - Ruby Meetup 27 Jun 2018Random Ruby Tips - Ruby Meetup 27 Jun 2018
Random Ruby Tips - Ruby Meetup 27 Jun 2018
 
Do you queue (updated)
Do you queue (updated)Do you queue (updated)
Do you queue (updated)
 
Supa fast Ruby + Rails
Supa fast Ruby + RailsSupa fast Ruby + Rails
Supa fast Ruby + Rails
 
td_mxc_rubyrails_shin
td_mxc_rubyrails_shintd_mxc_rubyrails_shin
td_mxc_rubyrails_shin
 
td_mxc_rubyrails_shin
td_mxc_rubyrails_shintd_mxc_rubyrails_shin
td_mxc_rubyrails_shin
 
MidwestPHP 2016 - Adventures in Laravel 5
MidwestPHP 2016 - Adventures in Laravel 5 MidwestPHP 2016 - Adventures in Laravel 5
MidwestPHP 2016 - Adventures in Laravel 5
 
Django design-patterns
Django design-patternsDjango design-patterns
Django design-patterns
 
AngularJS Beginner Day One
AngularJS Beginner Day OneAngularJS Beginner Day One
AngularJS Beginner Day One
 

More from Marakana Inc.

Android Services Black Magic by Aleksandar Gargenta
Android Services Black Magic by Aleksandar GargentaAndroid Services Black Magic by Aleksandar Gargenta
Android Services Black Magic by Aleksandar GargentaMarakana Inc.
 
Behavior Driven Development
Behavior Driven DevelopmentBehavior Driven Development
Behavior Driven DevelopmentMarakana Inc.
 
Martin Odersky: What's next for Scala
Martin Odersky: What's next for ScalaMartin Odersky: What's next for Scala
Martin Odersky: What's next for ScalaMarakana Inc.
 
Why Java Needs Hierarchical Data
Why Java Needs Hierarchical DataWhy Java Needs Hierarchical Data
Why Java Needs Hierarchical DataMarakana Inc.
 
Deep Dive Into Android Security
Deep Dive Into Android SecurityDeep Dive Into Android Security
Deep Dive Into Android SecurityMarakana Inc.
 
Pictures from "Learn about RenderScript" meetup at SF Android User Group
Pictures from "Learn about RenderScript" meetup at SF Android User GroupPictures from "Learn about RenderScript" meetup at SF Android User Group
Pictures from "Learn about RenderScript" meetup at SF Android User GroupMarakana Inc.
 
Android UI Tips, Tricks and Techniques
Android UI Tips, Tricks and TechniquesAndroid UI Tips, Tricks and Techniques
Android UI Tips, Tricks and TechniquesMarakana Inc.
 
2010 07-18.wa.rails tdd-6
2010 07-18.wa.rails tdd-62010 07-18.wa.rails tdd-6
2010 07-18.wa.rails tdd-6Marakana Inc.
 
Graphicsand animations devoxx2010 (1)
Graphicsand animations devoxx2010 (1)Graphicsand animations devoxx2010 (1)
Graphicsand animations devoxx2010 (1)Marakana Inc.
 
What's this jQuery? Where it came from, and how it will drive innovation
What's this jQuery? Where it came from, and how it will drive innovationWhat's this jQuery? Where it came from, and how it will drive innovation
What's this jQuery? Where it came from, and how it will drive innovationMarakana Inc.
 
jQuery State of the Union - Yehuda Katz
jQuery State of the Union - Yehuda KatzjQuery State of the Union - Yehuda Katz
jQuery State of the Union - Yehuda KatzMarakana Inc.
 
Pics from: "James Gosling on Apple, Apache, Google, Oracle and the Future of ...
Pics from: "James Gosling on Apple, Apache, Google, Oracle and the Future of ...Pics from: "James Gosling on Apple, Apache, Google, Oracle and the Future of ...
Pics from: "James Gosling on Apple, Apache, Google, Oracle and the Future of ...Marakana Inc.
 
Learn about JRuby Internals from one of the JRuby Lead Developers, Thomas Enebo
Learn about JRuby Internals from one of the JRuby Lead Developers, Thomas EneboLearn about JRuby Internals from one of the JRuby Lead Developers, Thomas Enebo
Learn about JRuby Internals from one of the JRuby Lead Developers, Thomas EneboMarakana Inc.
 
Replacing Java Incrementally
Replacing Java IncrementallyReplacing Java Incrementally
Replacing Java IncrementallyMarakana Inc.
 
Learn to Build like you Code with Apache Buildr
Learn to Build like you Code with Apache BuildrLearn to Build like you Code with Apache Buildr
Learn to Build like you Code with Apache BuildrMarakana Inc.
 
Learn How to Unit Test Your Android Application (with Robolectric)
Learn How to Unit Test Your Android Application (with Robolectric)Learn How to Unit Test Your Android Application (with Robolectric)
Learn How to Unit Test Your Android Application (with Robolectric)Marakana Inc.
 
Learn Learn how to build your mobile back-end with MongoDB
Learn Learn how to build your mobile back-end with MongoDBLearn Learn how to build your mobile back-end with MongoDB
Learn Learn how to build your mobile back-end with MongoDBMarakana Inc.
 
A hands on overview of the semantic web
A hands on overview of the semantic webA hands on overview of the semantic web
A hands on overview of the semantic webMarakana Inc.
 

More from Marakana Inc. (20)

Android Services Black Magic by Aleksandar Gargenta
Android Services Black Magic by Aleksandar GargentaAndroid Services Black Magic by Aleksandar Gargenta
Android Services Black Magic by Aleksandar Gargenta
 
JRuby at Square
JRuby at SquareJRuby at Square
JRuby at Square
 
Behavior Driven Development
Behavior Driven DevelopmentBehavior Driven Development
Behavior Driven Development
 
Martin Odersky: What's next for Scala
Martin Odersky: What's next for ScalaMartin Odersky: What's next for Scala
Martin Odersky: What's next for Scala
 
Why Java Needs Hierarchical Data
Why Java Needs Hierarchical DataWhy Java Needs Hierarchical Data
Why Java Needs Hierarchical Data
 
Deep Dive Into Android Security
Deep Dive Into Android SecurityDeep Dive Into Android Security
Deep Dive Into Android Security
 
Securing Android
Securing AndroidSecuring Android
Securing Android
 
Pictures from "Learn about RenderScript" meetup at SF Android User Group
Pictures from "Learn about RenderScript" meetup at SF Android User GroupPictures from "Learn about RenderScript" meetup at SF Android User Group
Pictures from "Learn about RenderScript" meetup at SF Android User Group
 
Android UI Tips, Tricks and Techniques
Android UI Tips, Tricks and TechniquesAndroid UI Tips, Tricks and Techniques
Android UI Tips, Tricks and Techniques
 
2010 07-18.wa.rails tdd-6
2010 07-18.wa.rails tdd-62010 07-18.wa.rails tdd-6
2010 07-18.wa.rails tdd-6
 
Graphicsand animations devoxx2010 (1)
Graphicsand animations devoxx2010 (1)Graphicsand animations devoxx2010 (1)
Graphicsand animations devoxx2010 (1)
 
What's this jQuery? Where it came from, and how it will drive innovation
What's this jQuery? Where it came from, and how it will drive innovationWhat's this jQuery? Where it came from, and how it will drive innovation
What's this jQuery? Where it came from, and how it will drive innovation
 
jQuery State of the Union - Yehuda Katz
jQuery State of the Union - Yehuda KatzjQuery State of the Union - Yehuda Katz
jQuery State of the Union - Yehuda Katz
 
Pics from: "James Gosling on Apple, Apache, Google, Oracle and the Future of ...
Pics from: "James Gosling on Apple, Apache, Google, Oracle and the Future of ...Pics from: "James Gosling on Apple, Apache, Google, Oracle and the Future of ...
Pics from: "James Gosling on Apple, Apache, Google, Oracle and the Future of ...
 
Learn about JRuby Internals from one of the JRuby Lead Developers, Thomas Enebo
Learn about JRuby Internals from one of the JRuby Lead Developers, Thomas EneboLearn about JRuby Internals from one of the JRuby Lead Developers, Thomas Enebo
Learn about JRuby Internals from one of the JRuby Lead Developers, Thomas Enebo
 
Replacing Java Incrementally
Replacing Java IncrementallyReplacing Java Incrementally
Replacing Java Incrementally
 
Learn to Build like you Code with Apache Buildr
Learn to Build like you Code with Apache BuildrLearn to Build like you Code with Apache Buildr
Learn to Build like you Code with Apache Buildr
 
Learn How to Unit Test Your Android Application (with Robolectric)
Learn How to Unit Test Your Android Application (with Robolectric)Learn How to Unit Test Your Android Application (with Robolectric)
Learn How to Unit Test Your Android Application (with Robolectric)
 
Learn Learn how to build your mobile back-end with MongoDB
Learn Learn how to build your mobile back-end with MongoDBLearn Learn how to build your mobile back-end with MongoDB
Learn Learn how to build your mobile back-end with MongoDB
 
A hands on overview of the semantic web
A hands on overview of the semantic webA hands on overview of the semantic web
A hands on overview of the semantic web
 

Recently uploaded

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
 
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
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024SynarionITSolutions
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdflior mazor
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 

Recently uploaded (20)

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
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 

Efficient Rails Test Driven Development (class 4) by Wolfram Arnold

  • 1. Efficient Rails Test-DrivenEfficient Rails Test-Driven Development — Week 4Development — Week 4 Wolfram ArnoldWolfram Arnold www.rubyfocus.bizwww.rubyfocus.biz In collaboration with:In collaboration with: Sarah Allen, BlazingCloud.netSarah Allen, BlazingCloud.net marakana.commarakana.com
  • 3. ControllersControllers Controllers are pass-through entities Mostly boilerplate—biz logic belongs in the model Controllers are “dumb” or “skinny” They follow a run-of-the mill pattern: the Controller Formula
  • 4. Controller RESTful ActionsController RESTful Actions Display methods (“Read”) GET: index, show, new, edit Update method PUT Create method POST Delete method DELETE
  • 5. REST?REST? Representational State Transfer All resource-based applications & API's need to do similar things, namely: create, read, update, delete It's a convention: no configuration, no ceremony superior to CORBA, SOAP, etc.
  • 6. RESTful rsources in RailsRESTful rsources in Rails map.resources :people (in config/routes.rb) people_path, people_url “named route methods” GET /people → “index” action POST /people → “create” action new_person_path, new_person_url GET /people/new → “new” action edit_person_path, edit_person_url GET /people/:id/edit → “edit” action with ID person_path, person_url GET /people/:id → “show” action with ID PUT /people/:id → “update” action with ID DELETE /people/:id → “destroy” action with ID
  • 7. Reads Test PatternReads Test Pattern Make request (with id of record if a single record) Check Rendering correct template redirect status code content type (HTML, JSON, XML,...) Verify Variable Assignments required by view
  • 8. Read FormulaRead Formula Find data, based on parameters Assign variables Render
  • 9. How much test is too much?How much test is too much? Test anything where the code deviates from defaults, e.g. redirect vs. straight up render These tests are not strictly necessary: response.should be_success response.should render_template('new') Test anything required for the application to proceed without error Speficially variable assignments Do test error handling code!
  • 10. form_for's automagic powersform_for's automagic powers form_for @person do |f| ... end When @person is new → <form action=”people” method=”post”> → PeopleController#create → uses people_path method to generate URL When @person exists already → <form action=”people” method=”put”> → PeopleController#update → uses person_path method to generate URL
  • 11. Create/Update Test PatternCreate/Update Test Pattern Make request with form fields to be created/upd'd Verify Variable Assignments Verify Check Success Rendering Verify Failure/Error Case Rendering Variables Verify HTTP Verb protection
  • 12. Create/Update FormulaCreate/Update Formula Update: Find record from parameters Create: Instantiate new model object Assign form fields parameters to model object This should be a single line It is a pattern, the “Controller Formula” Save Handle success—typically a redirect Handle failure—typically a render
  • 13. Destroy Test PatternDestroy Test Pattern Make request with id of record to be destroyed Rendering Typically no need to check for success or failure Invalid item referenced → Same behavior as read Database deletion failed → System not user error
  • 14. Destroy FormulaDestroy Formula Find record from parameters Destroy Redirect
  • 15. How much is enough?How much is enough? Notice: No view testing so far. Emphasize behavior over display. Check that the application handles errors correctly Test views only for things that could go wrong badly incorrect form URL incorrect names on complicated forms, because they impact parameter representation
  • 16. View TestingView Testing RSpec controllers do not render views (by default) Test form urls, any logic and input names Understand CSS selector syntax View test requires set up of variables another reason why there should only be very few variables between controller and view
  • 17. A note on RJSA note on RJS RJS lets you render a JS response using “RJS” Built on Prototype JS framework Hard to test Largely superseded by RSpec tested controllers responding in JSON JS tests mocking the server response jQuery's Ajax library very helpful
  • 18. RSpec Scaffold & MocksRSpec Scaffold & Mocks RSpec Scaffold mocks models Their philosophy is outside-in development I'm not a fan of this because: It causes gaps in coverage Mocks need to be maintained Outside-in remains unproven beyond textbook examples When taken to the extreme, it can become un-Agile by over-specifying the application
  • 20. One Form—Multiple ModelsOne Form—Multiple Models DB schema should not limit view/form layout View/form layout should not impose DB schema A single form to manipulate associated rows of multiple tables. → Nested Attributes
  • 21. View & Model CollaborationView & Model Collaboration Model: accepts_nested_attributes_for View: form_for fields_for Controller is unaware! Strictly pass-through Person.new(params[:person])
  • 22. accepts_nested_attributes_foraccepts_nested_attributes_for class Person < ActiveRecord::Base has_many :addresses accepts_nested_attributes_for :addresses end Person.create(:first_name => “Joe”, :last_name => “Smith”, :addresses_attributes => [ { :street => “123 Main, :city => “San Francisco”, :zip => “94103”, :state => “CA” } ]
  • 23. Nested Attributes New & OldNested Attributes New & Old A new record is recognized by absence of an id: :address_attributes => [ {:city => “SF”, :zip => “12345”, :street => “123 Main”, :state => “CA”} ] An existing record is recognized by presence of an id: :address_attributes => [ { :id => “5”, :city => “SF”, :zip => “12345”, :street => “123 Main”, :state => “CA”} ]
  • 24. Nested Attr's Singular & PluralNested Attr's Singular & Plural has_many :addresses :addresses_attributes => [ { record1 }, { record2 } ] has_one :address_of_record :address_attributes => { record }
  • 25. Nested Attributes ParametersNested Attributes Parameters :allow_destroy => true removes an existing record with _destroy => '1' default is false :reject_if => :method or Proc.new { |attrs| ... } suppresses creation or updating when false can pass :all_blank to skip records with all blank attr's :limit => 5 limits numbers of records creatable from nested attr's :update_only prevents multiple records for 1-on-1 associations
  • 26. Textbook Outside-In BDDTextbook Outside-In BDD Yes... Helps to lay out model requirements via mocks But... Mocks get out of sync A lot more work for not very much improved coverage Best place is exploratory testing Does nothing to encourage fat model/skinny controller paradigm Knowledge of advanced model features still key
  • 27. Value-Driven Outside-In BDDValue-Driven Outside-In BDD Write controller tests first Make them pending while fleshing out model Implement model logic with nested_scopes associations, with rich options & proxy methods accepts_nested_attributes_for Resume controller test Add views Exploratory Cucumber/Selenium test to avoid test gap between view & controller
  • 29. HomeworkHomework As a person, I can update my name along with an addresses on the same form. Extra credit: Using JavaScript, create an “add one” link on the new form that replicates the address sub-form, to permit entering more than one address. Same for a delete link. Reuse the above mechanism for the edit form.
  • 30. Recommended ReadingRecommended Reading http://railscasts.com/episodes/196-nested-model-form-part-1 http://asciicasts.com/episodes/196-nested-model-form-part-1 http://railscasts.com/episodes/197-nested-model-form-part-2 http://asciicasts.com/episodes/197-nested-model-form-part-2 http://docs.jquery.com/Main_Page http://activescaffold.com/ Nested Attributes API Docs: http://bit.ly/7cnt0 Form for (with nest'd attr's) API Docs: http://bit.ly/9DAscq My presentation on nested attributes: http://blip.tv/file/3957941 RSpec book chapters 1.5, 10, 11 (on BDD) RSpec book chapter 20 (outside-in development)
  • 31. Flickr Photo Attribute CreditFlickr Photo Attribute Credit Matroshka nested dolls http://www.flickr.com/photos/shereen84/2511071028/sizes/l/ Notebook with pencil http://www.flickr.com/photos/tomsaint/2987926396/sizes/l/ Control Panel http://www.flickr.com/photos/900hp/3961052527/sizes/l/