SlideShare a Scribd company logo
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

More Related Content

What's hot

RSpec: What, How and Why
RSpec: What, How and WhyRSpec: What, How and Why
RSpec: What, How and Why
Ratan Sebastian
 
Djangocon 2014 angular + django
Djangocon 2014 angular + djangoDjangocon 2014 angular + django
Djangocon 2014 angular + django
Nina Zakharenko
 
Django REST Framework
Django REST FrameworkDjango REST Framework
Django REST Framework
Load Impact
 
Testing Javascript with Jasmine
Testing Javascript with JasmineTesting Javascript with Jasmine
Testing Javascript with Jasmine
Tim Tyrrell
 
RSpec User Stories
RSpec User StoriesRSpec User Stories
RSpec User Stories
rahoulb
 
TDD with PhpSpec
TDD with PhpSpecTDD with PhpSpec
TDD with PhpSpec
CiaranMcNulty
 
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
Christopher 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 Dredd
Ryan M Harrison
 
Testing in AngularJS
Testing in AngularJSTesting in AngularJS
Testing in AngularJS
Peter Drinnan
 
Zero to Testing in JavaScript
Zero to Testing in JavaScriptZero to Testing in JavaScript
Zero to Testing in JavaScriptpamselle
 
I18n
I18nI18n
I18nsoon
 
RSpec
RSpecRSpec
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
Ynon 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 AngularJS
Almog Baku
 
Integration and Acceptance Testing
Integration and Acceptance TestingIntegration and Acceptance Testing
Integration and Acceptance Testing
Alan 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 Spray
Matthew Farwell
 
Scalable web application architecture
Scalable web application architectureScalable web application architecture
Scalable web application architecture
postrational
 
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
olegmmiller
 

What's hot (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
 

Viewers also liked

An Introduction to Faye
An Introduction to FayeAn Introduction to Faye
An Introduction to Faye
Darren 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 Scarring
leadingedgehealth
 
ドメインロジックの実装方法とドメイン駆動設計
ドメインロジックの実装方法とドメイン駆動設計ドメインロジックの実装方法とドメイン駆動設計
ドメインロジックの実装方法とドメイン駆動設計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 gRPC
Tim Burks
 
Gocon2017:Goのロギング周りの考察
Gocon2017:Goのロギング周りの考察Gocon2017:Goのロギング周りの考察
Gocon2017:Goのロギング周りの考察
貴仁 大和屋
 

Viewers also liked (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 to 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 tests
Oto Brglez
 
Cucumber & BDD
Cucumber & BDDCucumber & BDD
Cucumber & BDD
Sam Davarnia
 
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 Rails
Nicholas Cancelliere
 
Ruby For Startups
Ruby For StartupsRuby For Startups
Ruby For Startups
Mike Subelsky
 
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 Framework
Daniel 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 2013
Brian Sam-Bodden
 
Good Coding Practices with JavaScript
Good Coding Practices with JavaScriptGood Coding Practices with JavaScript
Good Coding Practices with JavaScript
🏁 Pierre-Henry Soria 💡
 
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 infrastructure
Lindsay Holmwood
 
Getting Started with React-Nathan Smith
Getting Started with React-Nathan SmithGetting Started with React-Nathan Smith
Getting Started with React-Nathan Smith
TandemSeven
 
Getting Started with React
Getting Started with ReactGetting Started with React
Getting Started with React
Nathan 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 2011
dimakovalenko
 

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

Recently uploaded

Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
Thijs Feryn
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
Dorra BARTAGUIZ
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
DianaGray10
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Jeffrey Haguewood
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Inflectra
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Ramesh Iyer
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
Cheryl Hung
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
Product School
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
91mobiles
 
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptxIOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
Abida Shariff
 
Search and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical FuturesSearch and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical Futures
Bhaskar Mitra
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
DianaGray10
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
Prayukth K V
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
Jemma Hussein Allen
 
НАДІЯ ФЕДЮШКО БАЦ «Професійне зростання QA спеціаліста»
НАДІЯ ФЕДЮШКО БАЦ  «Професійне зростання QA спеціаліста»НАДІЯ ФЕДЮШКО БАЦ  «Професійне зростання QA спеціаліста»
НАДІЯ ФЕДЮШКО БАЦ «Професійне зростання QA спеціаліста»
QADay
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
Paul Groth
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
Elena Simperl
 

Recently uploaded (20)

Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
 
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptxIOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
 
Search and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical FuturesSearch and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical Futures
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
 
НАДІЯ ФЕДЮШКО БАЦ «Професійне зростання QA спеціаліста»
НАДІЯ ФЕДЮШКО БАЦ  «Професійне зростання QA спеціаліста»НАДІЯ ФЕДЮШКО БАЦ  «Професійне зростання QA спеціаліста»
НАДІЯ ФЕДЮШКО БАЦ «Професійне зростання QA спеціаліста»
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
 

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