SlideShare a Scribd company logo
1 of 28
Download to read offline
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

More Related Content

What's hot

Quiz app (android) Documentation
Quiz app (android) DocumentationQuiz app (android) Documentation
Quiz app (android) DocumentationAditya Nag
 
Java 8 : Un ch'ti peu de lambda
Java 8 : Un ch'ti peu de lambdaJava 8 : Un ch'ti peu de lambda
Java 8 : Un ch'ti peu de lambdaCh'ti JUG
 
Quiz application
Quiz applicationQuiz application
Quiz applicationHarsh Verma
 
Aws certification-101
Aws certification-101Aws certification-101
Aws certification-101Noel Healy
 
Minor project Report for "Quiz Application"
Minor project Report for "Quiz Application"Minor project Report for "Quiz Application"
Minor project Report for "Quiz Application"Harsh Verma
 
Load Testing with k6 framework
Load Testing with k6 frameworkLoad Testing with k6 framework
Load Testing with k6 frameworkSvetlin Nakov
 
automation framework
automation frameworkautomation framework
automation frameworkANSHU GOYAL
 
Cypress-vs-Playwright-Rematch-Applitools.pdf
Cypress-vs-Playwright-Rematch-Applitools.pdfCypress-vs-Playwright-Rematch-Applitools.pdf
Cypress-vs-Playwright-Rematch-Applitools.pdfApplitools
 
Angular vs React vs Vue | Javascript Frameworks Comparison | Which One You Sh...
Angular vs React vs Vue | Javascript Frameworks Comparison | Which One You Sh...Angular vs React vs Vue | Javascript Frameworks Comparison | Which One You Sh...
Angular vs React vs Vue | Javascript Frameworks Comparison | Which One You Sh...Edureka!
 
Spring - Part 2 - Autowiring, Annotations, Java based Configuration - slides
Spring - Part 2 - Autowiring, Annotations, Java based Configuration - slidesSpring - Part 2 - Autowiring, Annotations, Java based Configuration - slides
Spring - Part 2 - Autowiring, Annotations, Java based Configuration - slidesHitesh-Java
 
Android Project Presentation
Android Project PresentationAndroid Project Presentation
Android Project PresentationLaxmi Kant Yadav
 

What's hot (20)

TestNG Framework
TestNG Framework TestNG Framework
TestNG Framework
 
JUnit Presentation
JUnit PresentationJUnit Presentation
JUnit Presentation
 
Quiz app (android) Documentation
Quiz app (android) DocumentationQuiz app (android) Documentation
Quiz app (android) Documentation
 
Java 8 : Un ch'ti peu de lambda
Java 8 : Un ch'ti peu de lambdaJava 8 : Un ch'ti peu de lambda
Java 8 : Un ch'ti peu de lambda
 
Quiz application
Quiz applicationQuiz application
Quiz application
 
Test Design with Action-based Testing Methodology - Ngo Hoang Minh
Test Design with Action-based Testing Methodology - Ngo Hoang MinhTest Design with Action-based Testing Methodology - Ngo Hoang Minh
Test Design with Action-based Testing Methodology - Ngo Hoang Minh
 
Aws certification-101
Aws certification-101Aws certification-101
Aws certification-101
 
Minor project Report for "Quiz Application"
Minor project Report for "Quiz Application"Minor project Report for "Quiz Application"
Minor project Report for "Quiz Application"
 
Load Testing with k6 framework
Load Testing with k6 frameworkLoad Testing with k6 framework
Load Testing with k6 framework
 
automation framework
automation frameworkautomation framework
automation framework
 
Android PPT
Android PPTAndroid PPT
Android PPT
 
Core java
Core javaCore java
Core java
 
Cypress-vs-Playwright-Rematch-Applitools.pdf
Cypress-vs-Playwright-Rematch-Applitools.pdfCypress-vs-Playwright-Rematch-Applitools.pdf
Cypress-vs-Playwright-Rematch-Applitools.pdf
 
AWS Webcast - Website Hosting
AWS Webcast - Website HostingAWS Webcast - Website Hosting
AWS Webcast - Website Hosting
 
Backend Programming
Backend ProgrammingBackend Programming
Backend Programming
 
Lombok
LombokLombok
Lombok
 
Angular vs React vs Vue | Javascript Frameworks Comparison | Which One You Sh...
Angular vs React vs Vue | Javascript Frameworks Comparison | Which One You Sh...Angular vs React vs Vue | Javascript Frameworks Comparison | Which One You Sh...
Angular vs React vs Vue | Javascript Frameworks Comparison | Which One You Sh...
 
iOS General Case Study
iOS General Case StudyiOS General Case Study
iOS General Case Study
 
Spring - Part 2 - Autowiring, Annotations, Java based Configuration - slides
Spring - Part 2 - Autowiring, Annotations, Java based Configuration - slidesSpring - Part 2 - Autowiring, Annotations, Java based Configuration - slides
Spring - Part 2 - Autowiring, Annotations, Java based Configuration - slides
 
Android Project Presentation
Android Project PresentationAndroid Project Presentation
Android Project Presentation
 

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

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

Recently uploaded

Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerThousandEyes
 
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceanilsa9823
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AIABDERRAOUF MEHENNI
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Steffen Staab
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...OnePlan Solutions
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsAndolasoft Inc
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...panagenda
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 

Recently uploaded (20)

Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 

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