SlideShare una empresa de Scribd logo
1 de 20
Descargar para leer sin conexión
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

Más contenido relacionado

La actualidad más candente

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
 

La actualidad más candente (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
 

Destacado

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のロギング周りの考察貴仁 大和屋
 

Destacado (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のロギング周りの考察
 

Similar a 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
 

Similar a 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
 

Último

08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
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
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
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
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
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
 

Último (20)

08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
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
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
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?
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
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
 

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