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

More Related Content

PPTX
Rest assured
PPTX
Testing RESTful web services with REST Assured
DOCX
Wipro resume
PPTX
[Final] ReactJS presentation
DOCX
Industrial Training report on java
DOCX
Core Java Training report
PDF
Core java course syllabus
PDF
automation testing benefits
Rest assured
Testing RESTful web services with REST Assured
Wipro resume
[Final] ReactJS presentation
Industrial Training report on java
Core Java Training report
Core java course syllabus
automation testing benefits

What's hot (20)

PDF
Unit Testing with Jest
PPT
Test Automation Framework Designs
PPTX
Test in Rest. API testing with the help of Rest Assured.
PDF
JUnit & Mockito, first steps
PPTX
React + Redux Introduction
PPTX
Automation Testing With Appium
PPS
JUnit Presentation
PPTX
Automation Framework Presentation
PPTX
API Testing Using REST Assured with TestNG
PDF
Appium: Automation for Mobile Apps
PPTX
Test your microservices with REST-Assured
PPTX
Automation - web testing with selenium
PDF
Selenium Page Object Model Using Page Factory | Selenium Tutorial For Beginne...
PDF
Spring annotation
PDF
Spring Framework - Core
PPT
Java script
PPTX
Introduction to React JS
PPT
Qtp Basics
PPTX
Lab #2: Introduction to Javascript
PDF
Styled components presentation
Unit Testing with Jest
Test Automation Framework Designs
Test in Rest. API testing with the help of Rest Assured.
JUnit & Mockito, first steps
React + Redux Introduction
Automation Testing With Appium
JUnit Presentation
Automation Framework Presentation
API Testing Using REST Assured with TestNG
Appium: Automation for Mobile Apps
Test your microservices with REST-Assured
Automation - web testing with selenium
Selenium Page Object Model Using Page Factory | Selenium Tutorial For Beginne...
Spring annotation
Spring Framework - Core
Java script
Introduction to React JS
Qtp Basics
Lab #2: Introduction to Javascript
Styled components presentation
Ad

Similar to Rspec (20)

KEY
Tdd for BT E2E test community
PDF
BDD style Unit Testing
PDF
Introduction to unit testing
PDF
2011-02-03 LA RubyConf Rails3 TDD Workshop
PPTX
RSpec: What, How and Why
PDF
Ruby on rails rspec
PDF
Rspec and Capybara Intro Tutorial at RailsConf 2013
PDF
Beyond Testing: Specs and Behavior Driven Development
PDF
PDF
Testing Ruby with Rspec (a beginner's guide)
PPTX
TDD with RSpec
PDF
WTF is TDD
PPTX
Intro to TDD and BDD
PDF
Rethinking Testing
PPTX
TDD & BDD
ZIP
Rspec Tips
PPT
Acceptance Testing With Selenium
PDF
2010-07-19_rails_tdd_week1
PDF
Basic RSpec 2
Tdd for BT E2E test community
BDD style Unit Testing
Introduction to unit testing
2011-02-03 LA RubyConf Rails3 TDD Workshop
RSpec: What, How and Why
Ruby on rails rspec
Rspec and Capybara Intro Tutorial at RailsConf 2013
Beyond Testing: Specs and Behavior Driven Development
Testing Ruby with Rspec (a beginner's guide)
TDD with RSpec
WTF is TDD
Intro to TDD and BDD
Rethinking Testing
TDD & BDD
Rspec Tips
Acceptance Testing With Selenium
2010-07-19_rails_tdd_week1
Basic RSpec 2
Ad

Recently uploaded (20)

PDF
Which alternative to Crystal Reports is best for small or large businesses.pdf
PDF
Understanding Forklifts - TECH EHS Solution
PPTX
Odoo POS Development Services by CandidRoot Solutions
PPTX
Introduction to Artificial Intelligence
PDF
How to Choose the Right IT Partner for Your Business in Malaysia
PDF
Wondershare Filmora 15 Crack With Activation Key [2025
PDF
Audit Checklist Design Aligning with ISO, IATF, and Industry Standards — Omne...
PDF
Design an Analysis of Algorithms I-SECS-1021-03
PPTX
ManageIQ - Sprint 268 Review - Slide Deck
PDF
Adobe Illustrator 28.6 Crack My Vision of Vector Design
PDF
Internet Downloader Manager (IDM) Crack 6.42 Build 41
PDF
How to Migrate SBCGlobal Email to Yahoo Easily
PPTX
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises
PDF
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
PDF
Odoo Companies in India – Driving Business Transformation.pdf
PPTX
ai tools demonstartion for schools and inter college
PPTX
CHAPTER 12 - CYBER SECURITY AND FUTURE SKILLS (1) (1).pptx
PPTX
Online Work Permit System for Fast Permit Processing
PPTX
Operating system designcfffgfgggggggvggggggggg
PPT
Introduction Database Management System for Course Database
Which alternative to Crystal Reports is best for small or large businesses.pdf
Understanding Forklifts - TECH EHS Solution
Odoo POS Development Services by CandidRoot Solutions
Introduction to Artificial Intelligence
How to Choose the Right IT Partner for Your Business in Malaysia
Wondershare Filmora 15 Crack With Activation Key [2025
Audit Checklist Design Aligning with ISO, IATF, and Industry Standards — Omne...
Design an Analysis of Algorithms I-SECS-1021-03
ManageIQ - Sprint 268 Review - Slide Deck
Adobe Illustrator 28.6 Crack My Vision of Vector Design
Internet Downloader Manager (IDM) Crack 6.42 Build 41
How to Migrate SBCGlobal Email to Yahoo Easily
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
Odoo Companies in India – Driving Business Transformation.pdf
ai tools demonstartion for schools and inter college
CHAPTER 12 - CYBER SECURITY AND FUTURE SKILLS (1) (1).pptx
Online Work Permit System for Fast Permit Processing
Operating system designcfffgfgggggggvggggggggg
Introduction Database Management System for Course Database

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