SlideShare une entreprise Scribd logo
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

Tendances (20)

Empower your App by Inheriting from Odoo Mixins
Empower your App by Inheriting from Odoo MixinsEmpower your App by Inheriting from Odoo Mixins
Empower your App by Inheriting from Odoo Mixins
 
ASP.NET MVC Presentation
ASP.NET MVC PresentationASP.NET MVC Presentation
ASP.NET MVC Presentation
 
Introduction to jQuery
Introduction to jQueryIntroduction to jQuery
Introduction to jQuery
 
Javascript
JavascriptJavascript
Javascript
 
Asp.net web api
Asp.net web apiAsp.net web api
Asp.net web api
 
jQuery Tutorial For Beginners | Developing User Interface (UI) Using jQuery |...
jQuery Tutorial For Beginners | Developing User Interface (UI) Using jQuery |...jQuery Tutorial For Beginners | Developing User Interface (UI) Using jQuery |...
jQuery Tutorial For Beginners | Developing User Interface (UI) Using jQuery |...
 
Builder pattern
Builder patternBuilder pattern
Builder pattern
 
Introduction to design patterns
Introduction to design patternsIntroduction to design patterns
Introduction to design patterns
 
Async History - javascript
Async History - javascriptAsync History - javascript
Async History - javascript
 
Domain driven design
Domain driven designDomain driven design
Domain driven design
 
ASP.NET Lecture 1
ASP.NET Lecture 1ASP.NET Lecture 1
ASP.NET Lecture 1
 
Jquery
JqueryJquery
Jquery
 
JNDI
JNDIJNDI
JNDI
 
react-js-notes-for-professionals-book.pdf
react-js-notes-for-professionals-book.pdfreact-js-notes-for-professionals-book.pdf
react-js-notes-for-professionals-book.pdf
 
Php sessions & cookies
Php sessions & cookiesPhp sessions & cookies
Php sessions & cookies
 
IBM websphere application server types of profiles
IBM websphere application server types of profilesIBM websphere application server types of profiles
IBM websphere application server types of profiles
 
Symfony Messenger (Symfony Live San Francisco)
Symfony Messenger (Symfony Live San Francisco)Symfony Messenger (Symfony Live San Francisco)
Symfony Messenger (Symfony Live San Francisco)
 
3. Java Script
3. Java Script3. Java Script
3. Java Script
 
My Sql Work Bench
My Sql Work BenchMy Sql Work Bench
My Sql Work Bench
 
C# Crystal Reports
C# Crystal ReportsC# Crystal Reports
C# Crystal Reports
 

Similaire à Rspec

Tdd for BT E2E test community
Tdd for BT E2E test communityTdd for BT E2E test community
Tdd for BT E2E test community
Kerry Buckley
 
Acceptance Testing With Selenium
Acceptance Testing With SeleniumAcceptance Testing With Selenium
Acceptance Testing With Selenium
elliando dias
 
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
Ran Mizrahi
 
540slidesofnodejsbackendhopeitworkforu.pdf
540slidesofnodejsbackendhopeitworkforu.pdf540slidesofnodejsbackendhopeitworkforu.pdf
540slidesofnodejsbackendhopeitworkforu.pdf
hamzadamani7
 
.NET Portfolio
.NET Portfolio.NET Portfolio
.NET Portfolio
mwillmer
 

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

Mastering Windows 7 A Comprehensive Guide for Power Users .pdf
Mastering Windows 7 A Comprehensive Guide for Power Users .pdfMastering Windows 7 A Comprehensive Guide for Power Users .pdf
Mastering Windows 7 A Comprehensive Guide for Power Users .pdf
mbmh111980
 
AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...
AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...
AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...
Alluxio, Inc.
 
JustNaik Solution Deck (stage bus sector)
JustNaik Solution Deck (stage bus sector)JustNaik Solution Deck (stage bus sector)
JustNaik Solution Deck (stage bus sector)
Max Lee
 

Dernier (20)

A Guideline to Gorgias to to Re:amaze Data Migration
A Guideline to Gorgias to to Re:amaze Data MigrationA Guideline to Gorgias to to Re:amaze Data Migration
A Guideline to Gorgias to to Re:amaze Data Migration
 
AI/ML Infra Meetup | ML explainability in Michelangelo
AI/ML Infra Meetup | ML explainability in MichelangeloAI/ML Infra Meetup | ML explainability in Michelangelo
AI/ML Infra Meetup | ML explainability in Michelangelo
 
A Comprehensive Appium Guide for Hybrid App Automation Testing.pdf
A Comprehensive Appium Guide for Hybrid App Automation Testing.pdfA Comprehensive Appium Guide for Hybrid App Automation Testing.pdf
A Comprehensive Appium Guide for Hybrid App Automation Testing.pdf
 
Mastering Windows 7 A Comprehensive Guide for Power Users .pdf
Mastering Windows 7 A Comprehensive Guide for Power Users .pdfMastering Windows 7 A Comprehensive Guide for Power Users .pdf
Mastering Windows 7 A Comprehensive Guide for Power Users .pdf
 
A Python-based approach to data loading in TM1 - Using Airflow as an ETL for TM1
A Python-based approach to data loading in TM1 - Using Airflow as an ETL for TM1A Python-based approach to data loading in TM1 - Using Airflow as an ETL for TM1
A Python-based approach to data loading in TM1 - Using Airflow as an ETL for TM1
 
Using IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New ZealandUsing IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New Zealand
 
Implementing KPIs and Right Metrics for Agile Delivery Teams.pdf
Implementing KPIs and Right Metrics for Agile Delivery Teams.pdfImplementing KPIs and Right Metrics for Agile Delivery Teams.pdf
Implementing KPIs and Right Metrics for Agile Delivery Teams.pdf
 
GraphSummit Stockholm - Neo4j - Knowledge Graphs and Product Updates
GraphSummit Stockholm - Neo4j - Knowledge Graphs and Product UpdatesGraphSummit Stockholm - Neo4j - Knowledge Graphs and Product Updates
GraphSummit Stockholm - Neo4j - Knowledge Graphs and Product Updates
 
AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...
AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...
AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
 
top nidhi software solution freedownload
top nidhi software solution freedownloadtop nidhi software solution freedownload
top nidhi software solution freedownload
 
JustNaik Solution Deck (stage bus sector)
JustNaik Solution Deck (stage bus sector)JustNaik Solution Deck (stage bus sector)
JustNaik Solution Deck (stage bus sector)
 
Agnieszka Andrzejewska - BIM School Course in Kraków
Agnieszka Andrzejewska - BIM School Course in KrakówAgnieszka Andrzejewska - BIM School Course in Kraków
Agnieszka Andrzejewska - BIM School Course in Kraków
 
Advanced Flow Concepts Every Developer Should Know
Advanced Flow Concepts Every Developer Should KnowAdvanced Flow Concepts Every Developer Should Know
Advanced Flow Concepts Every Developer Should Know
 
CompTIA Security+ (Study Notes) for cs.pdf
CompTIA Security+ (Study Notes) for cs.pdfCompTIA Security+ (Study Notes) for cs.pdf
CompTIA Security+ (Study Notes) for cs.pdf
 
AI/ML Infra Meetup | Perspective on Deep Learning Framework
AI/ML Infra Meetup | Perspective on Deep Learning FrameworkAI/ML Infra Meetup | Perspective on Deep Learning Framework
AI/ML Infra Meetup | Perspective on Deep Learning Framework
 
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBrokerSOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBroker
 
GraphAware - Transforming policing with graph-based intelligence analysis
GraphAware - Transforming policing with graph-based intelligence analysisGraphAware - Transforming policing with graph-based intelligence analysis
GraphAware - Transforming policing with graph-based intelligence analysis
 
Crafting the Perfect Measurement Sheet with PLM Integration
Crafting the Perfect Measurement Sheet with PLM IntegrationCrafting the Perfect Measurement Sheet with PLM Integration
Crafting the Perfect Measurement Sheet with PLM Integration
 
Benefits of Employee Monitoring Software
Benefits of  Employee Monitoring SoftwareBenefits of  Employee Monitoring Software
Benefits of Employee Monitoring Software
 

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