SlideShare une entreprise Scribd logo
1  sur  28
Télécharger pour lire hors ligne
Unit testing with RSpec
Amitai Barnea
2018
Types of Tests
Unit tests
Integration tests
End to End tests
Load tests
UI tests
Manual tests
What is a unit tests?
A unit test is a piece of a code (usually a method) that
invokes another piece of code and checks the
correctness of some assumptions after-ward. If the
assumptions turn out to be wrong, the unit test has
failed.
The impotance of unit tests
Unit testing makes projects a lot more effective at
delivering the correct solution in a predictable and
managed way.
The advantage of unit testing
Executing unit tests doesn't require the
application to be running.
It can be done before the whole application (or
module) is built.
More con dent in deploying code that is covered
by unit tests.
The unit tests document the code, and shows how
to use it.
The disadvantages of unit tests
It takes time to write them.
It takes time to run them (in sourcery it took us
more than 1 hour).
It takes time to maintain them after the code had
changed.
How to write good unit tests
Readability: Writing test code that is easy to
understand and communicates well
Maintainability: Writing tests that are robust and
hold up well over time
Automation: Writing tests that require little
setup and con guration (preferably none)
A word about TDD
TDD is "Test driven development"
The circle of TDD:
Test fail
Test pass
Refactor
Very helpful in some scenarios (I use it from time
to time).
RSpec
RSpec is a Behaviour-Driven Development tool for
Ruby programmers. BDD is an approach
to software development that combines Test-Driven
Development, Domain Driven Design,
and Acceptance Test-Driven Planning. RSpec helps
you do the TDD part of that equation,
focusing on the documentation and design aspects of
TDD.
Example
# game_spec.rb
RSpec.describe Calculator do
describe "#add" do
it "returns correct result" do
calculator = Calculator.new
res = calculator.add(5,6)
expect(res).to eq(11)
end
end
end
Test sructure
context - the context of the tests
describe - description of what we are testing
it - what do we expect the result will be.
context 'divide' do
describe 'verify it divide non zero number' do
it 'should return a correct result' do
expect(CalcHelper.divide(8,4)).to eq(3)
end
end
end
What do we test?
Golden scenarion
Each case the method has, it means every if, loop,
switch and so on.
Unreasonable parameters
def divide(a,b)
return a/b unless b.zero?
end
describe 'verify it divide non zero number' do
it 'should return a correct result' do
expect(CalcHelper.divide(8,4)).to eq(3)
end
end
describe 'verify it divide zero number will not raise an excepti
it 'should return nil' do
expect(CalcHelper.divide(8,0)).to eq(nil)
end
end
describe 'verify the parameters' do
it 'should return nil' do
expect(CalcHelper.divide('blabla',6)).to eq(nil)
end
end
The result helps us understand
what went wrong
Failures:
1) CalcHelper divide verify it divide non zero number should
Failure/Error: expect(CalcHelper.divide(8,4)).to eq(3)
expected: 3
got: 2
(compared using ==)
# ./spec/helpers/test_helper.rb:11:in `block (4 levels) in
Finished in 0.89486 seconds (files took 12.31 seconds to load
1 example, 1 failure
What can we test with RSpec
Models
Controllers
Helpers
Anything else...
Testing models
RSpec.describe AccountExpert, type: :model do
context 'fields' do
it { should respond_to(:account) }
it { should respond_to(:user) }
it { should respond_to(:specialization_subcategory) }
it { should respond_to(:specialization_subject) }
end
context 'creation' do
it 'should succeed' do
acc = Account.create(org_name: 'account1')
AccountExpert.create(user: @user, account: acc)
expect(AccountExpert.count).to eq(1)
end
end
end
Test model validations
context 'User fields validations' do
it 'first_name' do
user.first_name = 'a' * 21
expect(user.valid?).to eq(false)
end
end
Test controllers
context 'admin' do
login_admin
describe 'index' do
it 'should get all activities' do
get :index
expect(response.status).to eq(200)
json_response = JSON.parse(response.body)
expect(json_response.count).to eq 1
expect(json_response[0]['name']).to eq 'Art'
expect(json_response[0]['department_name']).to
eq 'Music'
end
end
end
Test helpers
describe QuestionaireHelper, type: :helper do
context 'when questionaire exist' do
it 'should return questionaire' do
@questionaire.executed_at = Time.now
@questionaire.save!
res = QHelper.find_daily(DateTime.now,@station, -1)
expect(res.id).to eq @questionaire.id
end
end
end
before
before do
@org = create :organization, name: 'BGU'
@org2 = create :organization
end
before :each
before :all
after - usually used to clean up after tests. The
best way is to clean the DB after each test using
database_cleaner.
Factories
help us create data fast with mimimum code
FactoryGirl - now called FactoryBot
FactoryGirl.define do
factory :activity do
sequence(:name) { |i| "activity #{i}" }
organization "Spectory"
department "Dev"
end
end
activity = create :activity, name: 'dev meeting'
Mocking, stubing, Facking
Instead of calling the real code, we call a mock that
will return our expected result
allow(Helper).to receive(:call)
allow(Helper).to receive(:call).and_return(result)
allow(Helper).to receive(:call).with(param).
and_return(result)
Spying
expect(Helper).to have_received(:select)
expect(Helper).to have_received(:select).with(param)
expect(Helper).to_not have_received(:select)
Handle exceptions
Notice the {} braces
expect{CalcHelper.divide(5,0)}.to raise_error
expect{CalcHelper.divide(5,0)}.to raise_error(ZeroDivisionError)
expect{CalcHelper.divide(5,0)}.to_not raise_error
Expect changes
Expect some code to change the state of some object
expect{Counter.increment}.to
change{Counter.count}.from(0).to(1)
Devise
Devise has gem that enable tests with RSpec
context 'instructor' do
login_instructor
describe 'index' do
it 'should get unauthorized error' do
get :index
expect(response.status).to eq(403)
end
end
end
Happy Coding :)
https://www.excella.com/insights/why-is-unit-
testing-important
https://relishapp.com/rspec

Contenu connexe

Tendances

Introduction to angular with a simple but complete project
Introduction to angular with a simple but complete projectIntroduction to angular with a simple but complete project
Introduction to angular with a simple but complete projectJadson Santos
 
Java servlets
Java servletsJava servlets
Java servletslopjuan
 
JavaOne 2013: Memory Efficient Java
JavaOne 2013: Memory Efficient JavaJavaOne 2013: Memory Efficient Java
JavaOne 2013: Memory Efficient JavaChris Bailey
 
Servlet.ppt
Servlet.pptServlet.ppt
Servlet.pptVMahesh5
 
Exception Handling in C#
Exception Handling in C#Exception Handling in C#
Exception Handling in C#Abid Kohistani
 
An Introduction to JUnit 5 and how to use it with Spring boot tests and Mockito
An Introduction to JUnit 5 and how to use it with Spring boot tests and MockitoAn Introduction to JUnit 5 and how to use it with Spring boot tests and Mockito
An Introduction to JUnit 5 and how to use it with Spring boot tests and Mockitoshaunthomas999
 
Introduction to hibernate
Introduction to hibernateIntroduction to hibernate
Introduction to hibernatehr1383
 
Spring boot introduction
Spring boot introductionSpring boot introduction
Spring boot introductionRasheed Waraich
 
Socket programming using java
Socket programming using javaSocket programming using java
Socket programming using javaUC San Diego
 

Tendances (20)

Introduction to java 8 stream api
Introduction to java 8 stream apiIntroduction to java 8 stream api
Introduction to java 8 stream api
 
Java - Sockets
Java - SocketsJava - Sockets
Java - Sockets
 
Test Automation Framework with BDD and Cucumber
Test Automation Framework with BDD and CucumberTest Automation Framework with BDD and Cucumber
Test Automation Framework with BDD and Cucumber
 
Jdbc
Jdbc   Jdbc
Jdbc
 
Introduction to angular with a simple but complete project
Introduction to angular with a simple but complete projectIntroduction to angular with a simple but complete project
Introduction to angular with a simple but complete project
 
Java servlets
Java servletsJava servlets
Java servlets
 
Java I/O
Java I/OJava I/O
Java I/O
 
Spring boot
Spring bootSpring boot
Spring boot
 
JavaOne 2013: Memory Efficient Java
JavaOne 2013: Memory Efficient JavaJavaOne 2013: Memory Efficient Java
JavaOne 2013: Memory Efficient Java
 
Servlet.ppt
Servlet.pptServlet.ppt
Servlet.ppt
 
Exception Handling in C#
Exception Handling in C#Exception Handling in C#
Exception Handling in C#
 
Angular routing
Angular routingAngular routing
Angular routing
 
An Introduction to JUnit 5 and how to use it with Spring boot tests and Mockito
An Introduction to JUnit 5 and how to use it with Spring boot tests and MockitoAn Introduction to JUnit 5 and how to use it with Spring boot tests and Mockito
An Introduction to JUnit 5 and how to use it with Spring boot tests and Mockito
 
Introduction to hibernate
Introduction to hibernateIntroduction to hibernate
Introduction to hibernate
 
BDD with Cucumber
BDD with CucumberBDD with Cucumber
BDD with Cucumber
 
Spring boot introduction
Spring boot introductionSpring boot introduction
Spring boot introduction
 
Java: GUI
Java: GUIJava: GUI
Java: GUI
 
Java tokens
Java tokensJava tokens
Java tokens
 
JUnit Presentation
JUnit PresentationJUnit Presentation
JUnit Presentation
 
Socket programming using java
Socket programming using javaSocket programming using java
Socket programming using java
 

Similaire à Rspec

Tdd for BT E2E test community
Tdd for BT E2E test communityTdd for BT E2E test community
Tdd for BT E2E test communityKerry Buckley
 
Acceptance Testing With Selenium
Acceptance Testing With SeleniumAcceptance Testing With Selenium
Acceptance Testing With Seleniumelliando dias
 
2011-02-03 LA RubyConf Rails3 TDD Workshop
2011-02-03 LA RubyConf Rails3 TDD Workshop2011-02-03 LA RubyConf Rails3 TDD Workshop
2011-02-03 LA RubyConf Rails3 TDD WorkshopWolfram Arnold
 
Grails unit testing
Grails unit testingGrails unit testing
Grails unit testingpleeps
 
Tdd is not about testing (OOP)
Tdd is not about testing (OOP)Tdd is not about testing (OOP)
Tdd is not about testing (OOP)Gianluca Padovani
 
The First C# Project Analyzed
The First C# Project AnalyzedThe First C# Project Analyzed
The First C# Project AnalyzedPVS-Studio
 
How To Test Everything
How To Test EverythingHow To Test Everything
How To Test Everythingnoelrap
 
Tdd pecha kucha_v2
Tdd pecha kucha_v2Tdd pecha kucha_v2
Tdd pecha kucha_v2Paul Boos
 
Looking for Bugs in MonoDevelop
Looking for Bugs in MonoDevelopLooking for Bugs in MonoDevelop
Looking for Bugs in MonoDevelopPVS-Studio
 
Test driven development in .Net - 2010 + Eclipse
Test driven development in .Net - 2010 + EclipseTest driven development in .Net - 2010 + Eclipse
Test driven development in .Net - 2010 + EclipseUTC Fire & Security
 
Intro To JavaScript Unit Testing - Ran Mizrahi
Intro To JavaScript Unit Testing - Ran MizrahiIntro To JavaScript Unit Testing - Ran Mizrahi
Intro To JavaScript Unit Testing - Ran MizrahiRan Mizrahi
 
540slidesofnodejsbackendhopeitworkforu.pdf
540slidesofnodejsbackendhopeitworkforu.pdf540slidesofnodejsbackendhopeitworkforu.pdf
540slidesofnodejsbackendhopeitworkforu.pdfhamzadamani7
 
Introduction to unit testing
Introduction to unit testingIntroduction to unit testing
Introduction to unit testingArtem Shoobovych
 
We continue checking Microsoft projects: analysis of PowerShell
We continue checking Microsoft projects: analysis of PowerShellWe continue checking Microsoft projects: analysis of PowerShell
We continue checking Microsoft projects: analysis of PowerShellPVS-Studio
 
.NET Portfolio
.NET Portfolio.NET Portfolio
.NET Portfoliomwillmer
 

Similaire à Rspec (20)

Tdd for BT E2E test community
Tdd for BT E2E test communityTdd for BT E2E test community
Tdd for BT E2E test community
 
Acceptance Testing With Selenium
Acceptance Testing With SeleniumAcceptance Testing With Selenium
Acceptance Testing With Selenium
 
2011-02-03 LA RubyConf Rails3 TDD Workshop
2011-02-03 LA RubyConf Rails3 TDD Workshop2011-02-03 LA RubyConf Rails3 TDD Workshop
2011-02-03 LA RubyConf Rails3 TDD Workshop
 
TDD & BDD
TDD & BDDTDD & BDD
TDD & BDD
 
Refactoring
RefactoringRefactoring
Refactoring
 
Oop lec 1
Oop lec 1Oop lec 1
Oop lec 1
 
Grails unit testing
Grails unit testingGrails unit testing
Grails unit testing
 
Tdd is not about testing (OOP)
Tdd is not about testing (OOP)Tdd is not about testing (OOP)
Tdd is not about testing (OOP)
 
The First C# Project Analyzed
The First C# Project AnalyzedThe First C# Project Analyzed
The First C# Project Analyzed
 
How To Test Everything
How To Test EverythingHow To Test Everything
How To Test Everything
 
Tdd pecha kucha_v2
Tdd pecha kucha_v2Tdd pecha kucha_v2
Tdd pecha kucha_v2
 
Looking for Bugs in MonoDevelop
Looking for Bugs in MonoDevelopLooking for Bugs in MonoDevelop
Looking for Bugs in MonoDevelop
 
Refactoring
RefactoringRefactoring
Refactoring
 
Test driven development in .Net - 2010 + Eclipse
Test driven development in .Net - 2010 + EclipseTest driven development in .Net - 2010 + Eclipse
Test driven development in .Net - 2010 + Eclipse
 
Intro To JavaScript Unit Testing - Ran Mizrahi
Intro To JavaScript Unit Testing - Ran MizrahiIntro To JavaScript Unit Testing - Ran Mizrahi
Intro To JavaScript Unit Testing - Ran Mizrahi
 
540slidesofnodejsbackendhopeitworkforu.pdf
540slidesofnodejsbackendhopeitworkforu.pdf540slidesofnodejsbackendhopeitworkforu.pdf
540slidesofnodejsbackendhopeitworkforu.pdf
 
UI Testing
UI TestingUI Testing
UI Testing
 
Introduction to unit testing
Introduction to unit testingIntroduction to unit testing
Introduction to unit testing
 
We continue checking Microsoft projects: analysis of PowerShell
We continue checking Microsoft projects: analysis of PowerShellWe continue checking Microsoft projects: analysis of PowerShell
We continue checking Microsoft projects: analysis of PowerShell
 
.NET Portfolio
.NET Portfolio.NET Portfolio
.NET Portfolio
 

Dernier

Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptxReal-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptxRTS corp
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based projectAnoyGreter
 
Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Rob Geurden
 
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)jennyeacort
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Velvetech LLC
 
Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Mater
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfFerryKemperman
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作qr0udbr0
 
Sending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdfSending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdf31events.com
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...OnePlan Solutions
 
Precise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalPrecise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalLionel Briand
 
Understanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM ArchitectureUnderstanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM Architecturerahul_net
 
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdf
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdfInnovate and Collaborate- Harnessing the Power of Open Source Software.pdf
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdfYashikaSharma391629
 
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Angel Borroy López
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odishasmiwainfosol
 
What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...Technogeeks
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtimeandrehoraa
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsAhmed Mohamed
 
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxUI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxAndreas Kunz
 

Dernier (20)

Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptxReal-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based project
 
Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...
 
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...
 
Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdf
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作
 
Sending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdfSending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdf
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
 
Precise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalPrecise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive Goal
 
Understanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM ArchitectureUnderstanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM Architecture
 
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdf
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdfInnovate and Collaborate- Harnessing the Power of Open Source Software.pdf
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdf
 
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
 
What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtime
 
2.pdf Ejercicios de programación competitiva
2.pdf Ejercicios de programación competitiva2.pdf Ejercicios de programación competitiva
2.pdf Ejercicios de programación competitiva
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML Diagrams
 
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxUI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
 

Rspec

  • 1. Unit testing with RSpec Amitai Barnea 2018
  • 2. Types of Tests Unit tests Integration tests End to End tests Load tests UI tests Manual tests
  • 3. What is a unit tests? A unit test is a piece of a code (usually a method) that invokes another piece of code and checks the correctness of some assumptions after-ward. If the assumptions turn out to be wrong, the unit test has failed.
  • 4. The impotance of unit tests Unit testing makes projects a lot more effective at delivering the correct solution in a predictable and managed way.
  • 5. The advantage of unit testing Executing unit tests doesn't require the application to be running. It can be done before the whole application (or module) is built. More con dent in deploying code that is covered by unit tests. The unit tests document the code, and shows how to use it.
  • 6. The disadvantages of unit tests It takes time to write them. It takes time to run them (in sourcery it took us more than 1 hour). It takes time to maintain them after the code had changed.
  • 7. How to write good unit tests Readability: Writing test code that is easy to understand and communicates well Maintainability: Writing tests that are robust and hold up well over time Automation: Writing tests that require little setup and con guration (preferably none)
  • 8. A word about TDD TDD is "Test driven development" The circle of TDD: Test fail Test pass Refactor Very helpful in some scenarios (I use it from time to time).
  • 9. RSpec RSpec is a Behaviour-Driven Development tool for Ruby programmers. BDD is an approach to software development that combines Test-Driven Development, Domain Driven Design, and Acceptance Test-Driven Planning. RSpec helps you do the TDD part of that equation, focusing on the documentation and design aspects of TDD.
  • 10. Example # game_spec.rb RSpec.describe Calculator do describe "#add" do it "returns correct result" do calculator = Calculator.new res = calculator.add(5,6) expect(res).to eq(11) end end end
  • 11. Test sructure context - the context of the tests describe - description of what we are testing it - what do we expect the result will be. context 'divide' do describe 'verify it divide non zero number' do it 'should return a correct result' do expect(CalcHelper.divide(8,4)).to eq(3) end end end
  • 12. What do we test? Golden scenarion Each case the method has, it means every if, loop, switch and so on. Unreasonable parameters def divide(a,b) return a/b unless b.zero? end
  • 13. describe 'verify it divide non zero number' do it 'should return a correct result' do expect(CalcHelper.divide(8,4)).to eq(3) end end describe 'verify it divide zero number will not raise an excepti it 'should return nil' do expect(CalcHelper.divide(8,0)).to eq(nil) end end describe 'verify the parameters' do it 'should return nil' do expect(CalcHelper.divide('blabla',6)).to eq(nil) end end
  • 14. The result helps us understand what went wrong Failures: 1) CalcHelper divide verify it divide non zero number should Failure/Error: expect(CalcHelper.divide(8,4)).to eq(3) expected: 3 got: 2 (compared using ==) # ./spec/helpers/test_helper.rb:11:in `block (4 levels) in Finished in 0.89486 seconds (files took 12.31 seconds to load 1 example, 1 failure
  • 15. What can we test with RSpec Models Controllers Helpers Anything else...
  • 16. Testing models RSpec.describe AccountExpert, type: :model do context 'fields' do it { should respond_to(:account) } it { should respond_to(:user) } it { should respond_to(:specialization_subcategory) } it { should respond_to(:specialization_subject) } end context 'creation' do it 'should succeed' do acc = Account.create(org_name: 'account1') AccountExpert.create(user: @user, account: acc) expect(AccountExpert.count).to eq(1) end end end
  • 17. Test model validations context 'User fields validations' do it 'first_name' do user.first_name = 'a' * 21 expect(user.valid?).to eq(false) end end
  • 18. Test controllers context 'admin' do login_admin describe 'index' do it 'should get all activities' do get :index expect(response.status).to eq(200) json_response = JSON.parse(response.body) expect(json_response.count).to eq 1 expect(json_response[0]['name']).to eq 'Art' expect(json_response[0]['department_name']).to eq 'Music' end end end
  • 19. Test helpers describe QuestionaireHelper, type: :helper do context 'when questionaire exist' do it 'should return questionaire' do @questionaire.executed_at = Time.now @questionaire.save! res = QHelper.find_daily(DateTime.now,@station, -1) expect(res.id).to eq @questionaire.id end end end
  • 20. before before do @org = create :organization, name: 'BGU' @org2 = create :organization end before :each before :all after - usually used to clean up after tests. The best way is to clean the DB after each test using database_cleaner.
  • 21. Factories help us create data fast with mimimum code FactoryGirl - now called FactoryBot FactoryGirl.define do factory :activity do sequence(:name) { |i| "activity #{i}" } organization "Spectory" department "Dev" end end activity = create :activity, name: 'dev meeting'
  • 22. Mocking, stubing, Facking Instead of calling the real code, we call a mock that will return our expected result allow(Helper).to receive(:call) allow(Helper).to receive(:call).and_return(result) allow(Helper).to receive(:call).with(param). and_return(result)
  • 24. Handle exceptions Notice the {} braces expect{CalcHelper.divide(5,0)}.to raise_error expect{CalcHelper.divide(5,0)}.to raise_error(ZeroDivisionError) expect{CalcHelper.divide(5,0)}.to_not raise_error
  • 25. Expect changes Expect some code to change the state of some object expect{Counter.increment}.to change{Counter.count}.from(0).to(1)
  • 26. Devise Devise has gem that enable tests with RSpec context 'instructor' do login_instructor describe 'index' do it 'should get unauthorized error' do get :index expect(response.status).to eq(403) end end end