SlideShare ist ein Scribd-Unternehmen logo
1 von 20
Downloaden Sie, um offline zu lesen
Rspec Best Practices
      Ruby Social Club Milano
           24 February 2011




                   Andrea Reginato
             twitter/andreareginato
I'll not teach RSpec
You have good books and web sites
                  The RSpec Book
            Rails Test Prescriptions




                   twitter/andreareginato
I'll tell you how I use RSpec
      What I've learned reading books
             some articles on the web
              but most important from
         my everyday job experience




                      twitter/andreareginato
Just a little introduction
 RSpec is a library that focus on
    testing the behavior of your
                everyday project




                  twitter/andreareginato
Why people do not use it
 Probably the testing practice is the
      most diffcult forma mentis a
            developer have to learn




                     twitter/andreareginato
It will save our life, maybe
  In the long term, you will not check
        your web page everytime you
     make a new feature, but you will
            check if your test passed




                      twitter/andreareginato
Short descriptions
# wrong
it "should have 422 status code if an
    unexpected params will be added" do
  response.should respond_with 422
end

# correct
context "when not valid"
  it { should respond_with 422 }
(over)use contexts
                          and use with/when as keys

# wrong
it "should have 200 status code if
    logged in" do
  response.should respond_with 200
end

# correct
context "when logged in" do
  it { should respond_with 200 }
end
Describe methods
# wrong
describe "the authenticate method for
           User logged in" ...
describe "if the user is an admin" do


# correct
describe ".authenticate" do
describe "#admin?"
Single expectation test
# wrong
it "should create a resource" do
  response.should respond_with_content_type(:json)
  response.should assign_to(:resource)
end


# correct
it { should respond_with_content_type(:json) }
it { should assign_to(:resource) }
Test the edge cases
# sample action
def destroy
  @resource = Resource.where(:id => params[:id])
  if @resource
    @resource.destroy
    head 204
  else
    render :template => "shared/404", :status => 404,
  end
end



What would you test ?
Test the edge case
# correct
describe "#destroy" do
  context "when resource is found" do
    it "should render_with 204"
    it "should assign @resource"
  context "when resource is not found" do
    it "should render with 404"
    it "should not assign @resource"
  end
end


Is this enough ?
Use the subject
# wrong
it { assigns("message").should match
     /The resource name is Genoveffa/ }
it { assigns("message").should match
     /it was born in Billyville/ }
it { assigns("message").creator.should match
     /Claudiano/ }

# correct
subject { assigns("message") }
it { should match /The resource name is Genoveffa/ }
it { should match /it was born in Billyville/ }
its(:creator) { should match /Claudiano/ }
Mock or not to mock
# wrong (a really personal point of view)
1) It's wrong when you never mock and recreate by code
a “medium complex” situation and it's time consuming
2) It's wrong when you mock everything. You have a light
system and the big advantage of independence, but you loose
part of the control on your application.

# correct
# simulate authenticated user
controller.stub!(:authenticate).and_return(true)
# simulate current user
controller.stub(:current_user).and_return(current_user)
# simulate not found record
Resource.stub(:where).with(created_from: id)
                     .and_return(false)
Create data when needed
# wrong
You shouldn't use fixtures
* loose control on our data
* load everything all the time
* difficult to find problems

# correct
describe "User"
  describe ".top" do
    before { 3.times { Factory(:user) } }
    it { User.top(2).should have(2).item }
  end
end
Shared examples to DRY
# wrong
context "when own resources" do
  it "should have it" do
    resource = Factory("user")
    do_get format: json
    assigns(users).should include(resource)
  end
end

context "when does not own resource" do
  it "should not have it" do
    not_owned_resource = Factory("unknown")
    do_get format: json
    assigns(users).should_not include(not_owned_resource)
  end
end
Shared examples to DRY
# correct (but why?)
shared_examples for "a secure resource" do
  context "when own the resource" do
    it "should have it" do
      resource = Factory("user")
      do_get format: json
      assigns(users).should include(resource)
    end
  end
  context "when does not own resource" do
    it "should not have it" do
      not_owned_resource = Factory("unknown")
      do_get format: json
      assigns(users).should_not include(not_owned_resource)
    end
  end
end
Shared examples to DRY
# correct (apply DRY on tests)
describe "#show" do
  it_should_behave_like "a secure resource"
  it_should_behave_like "a findable resource"
  it_should_behave_like "a secure resource"
  context "when not logged in" do
    it_should_handle "a not authenticated request"
  end
end
More?
# wrong
Do not use RSpec

# correct
Start using RSpec 2 into your next project
Thanks
# more info
Click here to fnd a public document with a
summary of all best practices


# contacts
andrea.reginato@gmail.com
twitter/andreareginato

Weitere ähnliche Inhalte

Was ist angesagt?

RSpec: What, How and Why
RSpec: What, How and WhyRSpec: What, How and Why
RSpec: What, How and WhyRatan Sebastian
 
Djangocon 2014 angular + django
Djangocon 2014 angular + djangoDjangocon 2014 angular + django
Djangocon 2014 angular + djangoNina Zakharenko
 
Django REST Framework
Django REST FrameworkDjango REST Framework
Django REST FrameworkLoad Impact
 
Testing Javascript with Jasmine
Testing Javascript with JasmineTesting Javascript with Jasmine
Testing Javascript with JasmineTim Tyrrell
 
RSpec User Stories
RSpec User StoriesRSpec User Stories
RSpec User Storiesrahoulb
 
Building an API with Django and Django REST Framework
Building an API with Django and Django REST FrameworkBuilding an API with Django and Django REST Framework
Building an API with Django and Django REST FrameworkChristopher Foresman
 
2019-08-23 API contract testing with Dredd
2019-08-23 API contract testing with Dredd2019-08-23 API contract testing with Dredd
2019-08-23 API contract testing with DreddRyan M Harrison
 
Testing in AngularJS
Testing in AngularJSTesting in AngularJS
Testing in AngularJSPeter Drinnan
 
Zero to Testing in JavaScript
Zero to Testing in JavaScriptZero to Testing in JavaScript
Zero to Testing in JavaScriptpamselle
 
I18n
I18nI18n
I18nsoon
 
How to write easy-to-test JavaScript
How to write easy-to-test JavaScriptHow to write easy-to-test JavaScript
How to write easy-to-test JavaScriptYnon Perek
 
The Best (and Worst) of Django
The Best (and Worst) of DjangoThe Best (and Worst) of Django
The Best (and Worst) of DjangoJacob Kaplan-Moss
 
Build REST API clients for AngularJS
Build REST API clients for AngularJSBuild REST API clients for AngularJS
Build REST API clients for AngularJSAlmog Baku
 
Integration and Acceptance Testing
Integration and Acceptance TestingIntegration and Acceptance Testing
Integration and Acceptance TestingAlan Hecht
 
Nexthink Library - replacing a ruby on rails application with Scala and Spray
Nexthink Library - replacing a ruby on rails application with Scala and SprayNexthink Library - replacing a ruby on rails application with Scala and Spray
Nexthink Library - replacing a ruby on rails application with Scala and SprayMatthew Farwell
 
Scalable web application architecture
Scalable web application architectureScalable web application architecture
Scalable web application architecturepostrational
 
Create a web-app with Cgi Appplication
Create a web-app with Cgi AppplicationCreate a web-app with Cgi Appplication
Create a web-app with Cgi Appplicationolegmmiller
 

Was ist angesagt? (20)

RSpec: What, How and Why
RSpec: What, How and WhyRSpec: What, How and Why
RSpec: What, How and Why
 
TDD with phpspec2
TDD with phpspec2TDD with phpspec2
TDD with phpspec2
 
Djangocon 2014 angular + django
Djangocon 2014 angular + djangoDjangocon 2014 angular + django
Djangocon 2014 angular + django
 
Django REST Framework
Django REST FrameworkDjango REST Framework
Django REST Framework
 
Testing Javascript with Jasmine
Testing Javascript with JasmineTesting Javascript with Jasmine
Testing Javascript with Jasmine
 
RSpec User Stories
RSpec User StoriesRSpec User Stories
RSpec User Stories
 
TDD with PhpSpec
TDD with PhpSpecTDD with PhpSpec
TDD with PhpSpec
 
Building an API with Django and Django REST Framework
Building an API with Django and Django REST FrameworkBuilding an API with Django and Django REST Framework
Building an API with Django and Django REST Framework
 
2019-08-23 API contract testing with Dredd
2019-08-23 API contract testing with Dredd2019-08-23 API contract testing with Dredd
2019-08-23 API contract testing with Dredd
 
Testing in AngularJS
Testing in AngularJSTesting in AngularJS
Testing in AngularJS
 
Zero to Testing in JavaScript
Zero to Testing in JavaScriptZero to Testing in JavaScript
Zero to Testing in JavaScript
 
I18n
I18nI18n
I18n
 
RSpec
RSpecRSpec
RSpec
 
How to write easy-to-test JavaScript
How to write easy-to-test JavaScriptHow to write easy-to-test JavaScript
How to write easy-to-test JavaScript
 
The Best (and Worst) of Django
The Best (and Worst) of DjangoThe Best (and Worst) of Django
The Best (and Worst) of Django
 
Build REST API clients for AngularJS
Build REST API clients for AngularJSBuild REST API clients for AngularJS
Build REST API clients for AngularJS
 
Integration and Acceptance Testing
Integration and Acceptance TestingIntegration and Acceptance Testing
Integration and Acceptance Testing
 
Nexthink Library - replacing a ruby on rails application with Scala and Spray
Nexthink Library - replacing a ruby on rails application with Scala and SprayNexthink Library - replacing a ruby on rails application with Scala and Spray
Nexthink Library - replacing a ruby on rails application with Scala and Spray
 
Scalable web application architecture
Scalable web application architectureScalable web application architecture
Scalable web application architecture
 
Create a web-app with Cgi Appplication
Create a web-app with Cgi AppplicationCreate a web-app with Cgi Appplication
Create a web-app with Cgi Appplication
 

Andere mochten auch

An Introduction to Faye
An Introduction to FayeAn Introduction to Faye
An Introduction to FayeDarren Oakley
 
Most Effective Ways Of Permanently Removing Keloid Scarring
Most Effective Ways Of Permanently Removing Keloid ScarringMost Effective Ways Of Permanently Removing Keloid Scarring
Most Effective Ways Of Permanently Removing Keloid Scarringleadingedgehealth
 
ドメインロジックの実装方法とドメイン駆動設計
ドメインロジックの実装方法とドメイン駆動設計ドメインロジックの実装方法とドメイン駆動設計
ドメインロジックの実装方法とドメイン駆動設計Tadayoshi Sato
 
C#実装から見るDDD(ドメイン駆動設計)
C#実装から見るDDD(ドメイン駆動設計)C#実装から見るDDD(ドメイン駆動設計)
C#実装から見るDDD(ドメイン駆動設計)Takuya Kawabe
 
GOCON Autumn (Story of our own Monitoring Agent in golang)
GOCON Autumn (Story of our own Monitoring Agent in golang)GOCON Autumn (Story of our own Monitoring Agent in golang)
GOCON Autumn (Story of our own Monitoring Agent in golang)Huy Do
 
Fast and Reliable Swift APIs with gRPC
Fast and Reliable Swift APIs with gRPCFast and Reliable Swift APIs with gRPC
Fast and Reliable Swift APIs with gRPCTim Burks
 
Gocon2017:Goのロギング周りの考察
Gocon2017:Goのロギング周りの考察Gocon2017:Goのロギング周りの考察
Gocon2017:Goのロギング周りの考察貴仁 大和屋
 

Andere mochten auch (7)

An Introduction to Faye
An Introduction to FayeAn Introduction to Faye
An Introduction to Faye
 
Most Effective Ways Of Permanently Removing Keloid Scarring
Most Effective Ways Of Permanently Removing Keloid ScarringMost Effective Ways Of Permanently Removing Keloid Scarring
Most Effective Ways Of Permanently Removing Keloid Scarring
 
ドメインロジックの実装方法とドメイン駆動設計
ドメインロジックの実装方法とドメイン駆動設計ドメインロジックの実装方法とドメイン駆動設計
ドメインロジックの実装方法とドメイン駆動設計
 
C#実装から見るDDD(ドメイン駆動設計)
C#実装から見るDDD(ドメイン駆動設計)C#実装から見るDDD(ドメイン駆動設計)
C#実装から見るDDD(ドメイン駆動設計)
 
GOCON Autumn (Story of our own Monitoring Agent in golang)
GOCON Autumn (Story of our own Monitoring Agent in golang)GOCON Autumn (Story of our own Monitoring Agent in golang)
GOCON Autumn (Story of our own Monitoring Agent in golang)
 
Fast and Reliable Swift APIs with gRPC
Fast and Reliable Swift APIs with gRPCFast and Reliable Swift APIs with gRPC
Fast and Reliable Swift APIs with gRPC
 
Gocon2017:Goのロギング周りの考察
Gocon2017:Goのロギング周りの考察Gocon2017:Goのロギング周りの考察
Gocon2017:Goのロギング周りの考察
 

Ähnlich wie RSpec 2 Best practices

Oto Brglez - Tips for better tests
Oto Brglez - Tips for better testsOto Brglez - Tips for better tests
Oto Brglez - Tips for better testsOto Brglez
 
Getting Up and Running with BDD on Rails
Getting Up and Running with BDD on RailsGetting Up and Running with BDD on Rails
Getting Up and Running with BDD on Railselliando dias
 
Getting Up and Running with BDD on Rails
Getting Up and Running with BDD on RailsGetting Up and Running with BDD on Rails
Getting Up and Running with BDD on RailsNicholas Cancelliere
 
Continuous (Production) Integration: Ruby on Rails Application Monitoring wit...
Continuous (Production) Integration: Ruby on Rails Application Monitoring wit...Continuous (Production) Integration: Ruby on Rails Application Monitoring wit...
Continuous (Production) Integration: Ruby on Rails Application Monitoring wit...jnewland
 
Crossing the Bridge: Connecting Rails and your Front-end Framework
Crossing the Bridge: Connecting Rails and your Front-end FrameworkCrossing the Bridge: Connecting Rails and your Front-end Framework
Crossing the Bridge: Connecting Rails and your Front-end FrameworkDaniel Spector
 
Rspec and Capybara Intro Tutorial at RailsConf 2013
Rspec and Capybara Intro Tutorial at RailsConf 2013Rspec and Capybara Intro Tutorial at RailsConf 2013
Rspec and Capybara Intro Tutorial at RailsConf 2013Brian Sam-Bodden
 
SharePoint Saturday NYC - SharePoint and jQuery, what I wish I would have kno...
SharePoint Saturday NYC - SharePoint and jQuery, what I wish I would have kno...SharePoint Saturday NYC - SharePoint and jQuery, what I wish I would have kno...
SharePoint Saturday NYC - SharePoint and jQuery, what I wish I would have kno...Mark Rackley
 
#SPSEMEA SharePoint & jQuery - What I wish I would have known a year ago..
#SPSEMEA SharePoint & jQuery - What I wish I would have known a year ago..#SPSEMEA SharePoint & jQuery - What I wish I would have known a year ago..
#SPSEMEA SharePoint & jQuery - What I wish I would have known a year ago..Mark Rackley
 
Connecting with the enterprise - The how and why of connecting to Enterprise ...
Connecting with the enterprise - The how and why of connecting to Enterprise ...Connecting with the enterprise - The how and why of connecting to Enterprise ...
Connecting with the enterprise - The how and why of connecting to Enterprise ...Kevin Poorman
 
Behaviour driven infrastructure
Behaviour driven infrastructureBehaviour driven infrastructure
Behaviour driven infrastructureLindsay Holmwood
 
Getting Started with React-Nathan Smith
Getting Started with React-Nathan SmithGetting Started with React-Nathan Smith
Getting Started with React-Nathan SmithTandemSeven
 
Getting Started with React
Getting Started with ReactGetting Started with React
Getting Started with ReactNathan Smith
 
Cucumber Presentation Kiev Meet Up
Cucumber Presentation Kiev Meet UpCucumber Presentation Kiev Meet Up
Cucumber Presentation Kiev Meet Updimakovalenko
 
Selenium and Cucumber Selenium Conf 2011
Selenium and Cucumber Selenium Conf 2011Selenium and Cucumber Selenium Conf 2011
Selenium and Cucumber Selenium Conf 2011dimakovalenko
 

Ähnlich wie RSpec 2 Best practices (20)

Oto Brglez - Tips for better tests
Oto Brglez - Tips for better testsOto Brglez - Tips for better tests
Oto Brglez - Tips for better tests
 
Cucumber & BDD
Cucumber & BDDCucumber & BDD
Cucumber & BDD
 
Getting Up and Running with BDD on Rails
Getting Up and Running with BDD on RailsGetting Up and Running with BDD on Rails
Getting Up and Running with BDD on Rails
 
Getting Up and Running with BDD on Rails
Getting Up and Running with BDD on RailsGetting Up and Running with BDD on Rails
Getting Up and Running with BDD on Rails
 
Ruby For Startups
Ruby For StartupsRuby For Startups
Ruby For Startups
 
Continuous (Production) Integration: Ruby on Rails Application Monitoring wit...
Continuous (Production) Integration: Ruby on Rails Application Monitoring wit...Continuous (Production) Integration: Ruby on Rails Application Monitoring wit...
Continuous (Production) Integration: Ruby on Rails Application Monitoring wit...
 
Having Fun with Play
Having Fun with PlayHaving Fun with Play
Having Fun with Play
 
Rtt preso
Rtt presoRtt preso
Rtt preso
 
Crossing the Bridge: Connecting Rails and your Front-end Framework
Crossing the Bridge: Connecting Rails and your Front-end FrameworkCrossing the Bridge: Connecting Rails and your Front-end Framework
Crossing the Bridge: Connecting Rails and your Front-end Framework
 
Rspec and Capybara Intro Tutorial at RailsConf 2013
Rspec and Capybara Intro Tutorial at RailsConf 2013Rspec and Capybara Intro Tutorial at RailsConf 2013
Rspec and Capybara Intro Tutorial at RailsConf 2013
 
Good Coding Practices with JavaScript
Good Coding Practices with JavaScriptGood Coding Practices with JavaScript
Good Coding Practices with JavaScript
 
SharePoint Saturday NYC - SharePoint and jQuery, what I wish I would have kno...
SharePoint Saturday NYC - SharePoint and jQuery, what I wish I would have kno...SharePoint Saturday NYC - SharePoint and jQuery, what I wish I would have kno...
SharePoint Saturday NYC - SharePoint and jQuery, what I wish I would have kno...
 
#SPSEMEA SharePoint & jQuery - What I wish I would have known a year ago..
#SPSEMEA SharePoint & jQuery - What I wish I would have known a year ago..#SPSEMEA SharePoint & jQuery - What I wish I would have known a year ago..
#SPSEMEA SharePoint & jQuery - What I wish I would have known a year ago..
 
Rails OO views
Rails OO viewsRails OO views
Rails OO views
 
Connecting with the enterprise - The how and why of connecting to Enterprise ...
Connecting with the enterprise - The how and why of connecting to Enterprise ...Connecting with the enterprise - The how and why of connecting to Enterprise ...
Connecting with the enterprise - The how and why of connecting to Enterprise ...
 
Behaviour driven infrastructure
Behaviour driven infrastructureBehaviour driven infrastructure
Behaviour driven infrastructure
 
Getting Started with React-Nathan Smith
Getting Started with React-Nathan SmithGetting Started with React-Nathan Smith
Getting Started with React-Nathan Smith
 
Getting Started with React
Getting Started with ReactGetting Started with React
Getting Started with React
 
Cucumber Presentation Kiev Meet Up
Cucumber Presentation Kiev Meet UpCucumber Presentation Kiev Meet Up
Cucumber Presentation Kiev Meet Up
 
Selenium and Cucumber Selenium Conf 2011
Selenium and Cucumber Selenium Conf 2011Selenium and Cucumber Selenium Conf 2011
Selenium and Cucumber Selenium Conf 2011
 

Kürzlich hochgeladen

DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxLoriGlavin3
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxLoriGlavin3
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESmohitsingh558521
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embeddingZilliz
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
What is Artificial Intelligence?????????
What is Artificial Intelligence?????????What is Artificial Intelligence?????????
What is Artificial Intelligence?????????blackmambaettijean
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxLoriGlavin3
 

Kürzlich hochgeladen (20)

DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embedding
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
What is Artificial Intelligence?????????
What is Artificial Intelligence?????????What is Artificial Intelligence?????????
What is Artificial Intelligence?????????
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
 

RSpec 2 Best practices

  • 1. Rspec Best Practices Ruby Social Club Milano 24 February 2011 Andrea Reginato twitter/andreareginato
  • 2. I'll not teach RSpec You have good books and web sites The RSpec Book Rails Test Prescriptions twitter/andreareginato
  • 3. I'll tell you how I use RSpec What I've learned reading books some articles on the web but most important from my everyday job experience twitter/andreareginato
  • 4. Just a little introduction RSpec is a library that focus on testing the behavior of your everyday project twitter/andreareginato
  • 5. Why people do not use it Probably the testing practice is the most diffcult forma mentis a developer have to learn twitter/andreareginato
  • 6. It will save our life, maybe In the long term, you will not check your web page everytime you make a new feature, but you will check if your test passed twitter/andreareginato
  • 7. Short descriptions # wrong it "should have 422 status code if an unexpected params will be added" do response.should respond_with 422 end # correct context "when not valid" it { should respond_with 422 }
  • 8. (over)use contexts and use with/when as keys # wrong it "should have 200 status code if logged in" do response.should respond_with 200 end # correct context "when logged in" do it { should respond_with 200 } end
  • 9. Describe methods # wrong describe "the authenticate method for User logged in" ... describe "if the user is an admin" do # correct describe ".authenticate" do describe "#admin?"
  • 10. Single expectation test # wrong it "should create a resource" do response.should respond_with_content_type(:json) response.should assign_to(:resource) end # correct it { should respond_with_content_type(:json) } it { should assign_to(:resource) }
  • 11. Test the edge cases # sample action def destroy @resource = Resource.where(:id => params[:id]) if @resource @resource.destroy head 204 else render :template => "shared/404", :status => 404, end end What would you test ?
  • 12. Test the edge case # correct describe "#destroy" do context "when resource is found" do it "should render_with 204" it "should assign @resource" context "when resource is not found" do it "should render with 404" it "should not assign @resource" end end Is this enough ?
  • 13. Use the subject # wrong it { assigns("message").should match /The resource name is Genoveffa/ } it { assigns("message").should match /it was born in Billyville/ } it { assigns("message").creator.should match /Claudiano/ } # correct subject { assigns("message") } it { should match /The resource name is Genoveffa/ } it { should match /it was born in Billyville/ } its(:creator) { should match /Claudiano/ }
  • 14. Mock or not to mock # wrong (a really personal point of view) 1) It's wrong when you never mock and recreate by code a “medium complex” situation and it's time consuming 2) It's wrong when you mock everything. You have a light system and the big advantage of independence, but you loose part of the control on your application. # correct # simulate authenticated user controller.stub!(:authenticate).and_return(true) # simulate current user controller.stub(:current_user).and_return(current_user) # simulate not found record Resource.stub(:where).with(created_from: id) .and_return(false)
  • 15. Create data when needed # wrong You shouldn't use fixtures * loose control on our data * load everything all the time * difficult to find problems # correct describe "User" describe ".top" do before { 3.times { Factory(:user) } } it { User.top(2).should have(2).item } end end
  • 16. Shared examples to DRY # wrong context "when own resources" do it "should have it" do resource = Factory("user") do_get format: json assigns(users).should include(resource) end end context "when does not own resource" do it "should not have it" do not_owned_resource = Factory("unknown") do_get format: json assigns(users).should_not include(not_owned_resource) end end
  • 17. Shared examples to DRY # correct (but why?) shared_examples for "a secure resource" do context "when own the resource" do it "should have it" do resource = Factory("user") do_get format: json assigns(users).should include(resource) end end context "when does not own resource" do it "should not have it" do not_owned_resource = Factory("unknown") do_get format: json assigns(users).should_not include(not_owned_resource) end end end
  • 18. Shared examples to DRY # correct (apply DRY on tests) describe "#show" do it_should_behave_like "a secure resource" it_should_behave_like "a findable resource" it_should_behave_like "a secure resource" context "when not logged in" do it_should_handle "a not authenticated request" end end
  • 19. More? # wrong Do not use RSpec # correct Start using RSpec 2 into your next project
  • 20. Thanks # more info Click here to fnd a public document with a summary of all best practices # contacts andrea.reginato@gmail.com twitter/andreareginato