SlideShare a Scribd company logo
1 of 9
Download to read offline
rspec matchers
Zaharie Marius - 06-03-2015
1 / 9
1. Composable matchers
Example:
#background_worker_spec.rb
describeBackgroundWorkerdo
it'putsenqueuedjobsontothequeueinorder'do
worker=BackgroundWorker.new
worker.enqueue(:klass=>"Class1",:id=>37)
worker.enqueue(:klass=>"Class2",:id=>42)
expect(worker.queue).tomatch[
a_hash_including(:klass=>"Class1",:id=>37),
a_hash_including(:klass=>"Class2",:id=>42)
]
end
end
a_hash_includingis an alias for the includematcher.
2 / 9
Aliases
RSpec 3 provides one or more aliases for all the built-in matchers.
consistent phrasing ("a_[type of object][verb]ing")
so they are easy to guess:
a_string_starting_withfor start_with
a_string_includinga_collection_includinga_hash_includingaliases
of include
see a list of them in this gist
easier to read when used in compound expresions or composed
matchers
and also more readable failure mssages.
RSpec 3 made it easy to define an alias for some built-in matcher or even your
custom matchers. Here is the bit of code to define the a_string_starting_with
alias of start_with:
RSpec::Matchers.alias_matcher:a_string_starting_with,:start_with
3 / 9
What are these composable matchers good for?
They will save you from this ...
describe"GET/api/areas/:area_id/pscs"do
context"whengivenvaliddata"do
it"returnsthePSCSforgivenareainJSON"do
get"/api/areas/#{area.id}/pscs",
{access_token:access_token_for(user),level_id:area.default_level.id},
{'Accept'=>Mime::JSON}
expect(response.status).tobe(200)
expect(response.content_type).tobe(Mime::JSON)
json_response=json(response.body)
expect(json_response[:latitude]).to eq(area.location.point.latitude.to_f)
expect(json_response[:longitude]).to eq(area.location.point.longitude.to_f)
#otherlongexpectshere
expect(level_node[:previous_level][:level_id]).toeq(area.parkings_levels.order_by_lev
expect(level_node[:image][:url]).to eq(area.level_image(area.default_leve
pscs_latitudes=json_response[:pscs].map{|e|e[:pscs][:latitude]}
expect(pscs_latitudes).toinclude(area.pscs_on_level(area.default_level.id).first.poin
end
end
end
4 / 9
The solution
is to use the matchmatcher, which became in rspec 3 a kind of black hole for any rspec
matcher.
describe"GET/api/areas/:area_id/pscs"do
context"whengivenvaliddata"do
it"returnsthePSCSforgivenareainJSON"do
get"/api/areas/#{area.id}/pscs",
{level_id:area.default_level.id},
{
'Authorization'=>"Bearer#{access_token_for(user)}",
'Accept'=>Mime::JSON
}
expect(response).tohave_status(200).and_content_type(Mime::JSON)
json_response=json(response.body)
expect(json_response).tomatch(pscs_list_composed_matcher(area:area))
expect(json_response[:pscs]).tocontain_latitude(area.pscs_on_level(area.default_level
end
end
end
5 / 9
The object passed to matchis more like a big hash containing any rspec
matchers as values for his keys:
modulePscsHelpers
defpscs_list_composed_matcher(area:,current_level:nil,is_favorite:false)
current_level=area.default_level
{
latitude:area.location.point.latitude.to_f,
longitude:area.location.point.longitude.to_f,
is_favorite:is_favorite,
zoomLevel:(a_value>0),
level:current_level_matcher(area,current_level),
pscs:an_instance_of(Array)
}
end
defcurrent_level_matcher(area,current_level)
{
level_id:current_level.id,
name:current_level.name,
default_level:level_matcher(area.default_level),
next_level: level_matcher(area.levels.first),
previous_level:level_matcher(area.levels.last),
image:level_image_matcher(area,current_level)
}
end
#reusable
deflevel_matcher(level)
#...
end
deflevel_image_matcher(area,current_level)
#... 6 / 9
2. Custom matchers
2.1 How to:
RSpec::Matchers.define:contain_latitudedo|expected|
latitudes=[]
matchdo|actual|
latitudes=actual.collect{|item|item[:pscs][:latitude]}
latitudes.find{|lat|lat.to_s==expected.to_s}
end
failure_messagedo|actual|
"expectedthatpscs_listwithlatitudesn #{latitudes}nwouldcontainthe'#{expec
end
end
#anduseitlikethis:
expect(json_response[:pscs]).tocontain_latitude(45.4545)
#orusingacompoundexpression
expect(json_response[:pscs])
.tocontain_latitude(45.4545)
.andcontain_longitude(25.90)
7 / 9
2.2 Chained matchers with fluent interface
When you want something more expressive then .andor .orfrom previous
example
modulePscsHelpers
#scopedmatcherswiththePscsHelpersmodule
extendRSpec::Matchers::DSL
matcher:contain_a_latitude_bigger_thando|first|
latitudes=[]
matchdo|actual|
latitudes=actual.collect{|item|item[:pscs][:latitude]}
bigger=latitudes.find{|lat|lat>expected}
smaller=latitudes.find{|lat|lat<second}
bigger&&smaller
end
chain:but_smaller_thando|second|
@second=second
end
end
end
#andthefancyexpectationusingit
expect(response).tocontain_a_latitude_bigger_than(43).but_smaller_than(47)
8 / 9
Resources
RSpec 3 - Composable Matchers
List of RSpec 3 Aliases gist
Define Matcher
9 / 9

More Related Content

What's hot

JavaScript Functions
JavaScript Functions JavaScript Functions
JavaScript Functions Reem Alattas
 
The art of readable code (ch1~ch4)
The art of readable code (ch1~ch4)The art of readable code (ch1~ch4)
The art of readable code (ch1~ch4)Ki Sung Bae
 
JavaScript Arrays
JavaScript Arrays JavaScript Arrays
JavaScript Arrays Reem Alattas
 
Lecture no 3
Lecture no 3Lecture no 3
Lecture no 3hasi071
 
Understanding Javascript Engine to Code Better
Understanding Javascript Engine to Code BetterUnderstanding Javascript Engine to Code Better
Understanding Javascript Engine to Code BetterIhsan Fauzi Rahman
 
Ruby Programming Language
Ruby Programming LanguageRuby Programming Language
Ruby Programming LanguageDuda Dornelles
 
Javascript built in String Functions
Javascript built in String FunctionsJavascript built in String Functions
Javascript built in String FunctionsAvanitrambadiya
 
Logic Equations Resolver J Script
Logic Equations Resolver   J ScriptLogic Equations Resolver   J Script
Logic Equations Resolver J ScriptRoman Agaev
 
JavaScript Proven Practises
JavaScript Proven PractisesJavaScript Proven Practises
JavaScript Proven PractisesRobert MacLean
 
Python 3.x Dictionaries and Sets Cheatsheet
Python 3.x Dictionaries and Sets CheatsheetPython 3.x Dictionaries and Sets Cheatsheet
Python 3.x Dictionaries and Sets CheatsheetIsham Rashik
 
Chaining and function composition with lodash / underscore
Chaining and function composition with lodash / underscoreChaining and function composition with lodash / underscore
Chaining and function composition with lodash / underscoreNicolas Carlo
 

What's hot (20)

What are arrays in java script
What are arrays in java scriptWhat are arrays in java script
What are arrays in java script
 
It6312 dbms lab-ex2
It6312 dbms lab-ex2It6312 dbms lab-ex2
It6312 dbms lab-ex2
 
cs8project
cs8projectcs8project
cs8project
 
JavaScript Functions
JavaScript Functions JavaScript Functions
JavaScript Functions
 
The art of readable code (ch1~ch4)
The art of readable code (ch1~ch4)The art of readable code (ch1~ch4)
The art of readable code (ch1~ch4)
 
JavaScript Arrays
JavaScript Arrays JavaScript Arrays
JavaScript Arrays
 
Lecture no 3
Lecture no 3Lecture no 3
Lecture no 3
 
Understanding Javascript Engine to Code Better
Understanding Javascript Engine to Code BetterUnderstanding Javascript Engine to Code Better
Understanding Javascript Engine to Code Better
 
Ruby Programming Language
Ruby Programming LanguageRuby Programming Language
Ruby Programming Language
 
Hamcrest
HamcrestHamcrest
Hamcrest
 
Lodash js
Lodash jsLodash js
Lodash js
 
Database security
Database securityDatabase security
Database security
 
Javascript built in String Functions
Javascript built in String FunctionsJavascript built in String Functions
Javascript built in String Functions
 
Logic Equations Resolver J Script
Logic Equations Resolver   J ScriptLogic Equations Resolver   J Script
Logic Equations Resolver J Script
 
JavaScript Proven Practises
JavaScript Proven PractisesJavaScript Proven Practises
JavaScript Proven Practises
 
Clojure functions midje
Clojure functions midjeClojure functions midje
Clojure functions midje
 
Java Cheat Sheet
Java Cheat SheetJava Cheat Sheet
Java Cheat Sheet
 
Java and xml
Java and xmlJava and xml
Java and xml
 
Python 3.x Dictionaries and Sets Cheatsheet
Python 3.x Dictionaries and Sets CheatsheetPython 3.x Dictionaries and Sets Cheatsheet
Python 3.x Dictionaries and Sets Cheatsheet
 
Chaining and function composition with lodash / underscore
Chaining and function composition with lodash / underscoreChaining and function composition with lodash / underscore
Chaining and function composition with lodash / underscore
 

Viewers also liked

Media Analysis of film opening: Media Language
Media Analysis of film opening: Media LanguageMedia Analysis of film opening: Media Language
Media Analysis of film opening: Media Languageelliotbrownnn
 
Restaurant floor manager kpi
Restaurant floor manager kpiRestaurant floor manager kpi
Restaurant floor manager kpidiretjom
 
Custom-Soft review system pune India
Custom-Soft review system pune IndiaCustom-Soft review system pune India
Custom-Soft review system pune IndiaHarshuV
 
Disastermanagementppt 130128141146-phpapp02
Disastermanagementppt 130128141146-phpapp02Disastermanagementppt 130128141146-phpapp02
Disastermanagementppt 130128141146-phpapp02Ram Krishna
 
1С-Битрикс "Разумная разработка интернет-магазина: функционал и сценарии работы"
1С-Битрикс "Разумная разработка интернет-магазина: функционал и сценарии работы"1С-Битрикс "Разумная разработка интернет-магазина: функционал и сценарии работы"
1С-Битрикс "Разумная разработка интернет-магазина: функционал и сценарии работы"awgua
 
Tik Bab 1 kelas 9
Tik Bab 1 kelas 9Tik Bab 1 kelas 9
Tik Bab 1 kelas 9dyahassifa
 
How to make kids grow taller
How to make kids grow tallerHow to make kids grow taller
How to make kids grow tallerkuppimicheal123
 
Consumer protection act 1986 akosha
Consumer protection act 1986  akoshaConsumer protection act 1986  akosha
Consumer protection act 1986 akoshaRavi Ramchandani
 
Rupicon 2014 useful design patterns in rails
Rupicon 2014 useful design patterns in railsRupicon 2014 useful design patterns in rails
Rupicon 2014 useful design patterns in railsrupicon
 
活動紹介2014ホームページ用
活動紹介2014ホームページ用活動紹介2014ホームページ用
活動紹介2014ホームページ用kiyokiyotaka
 
Portafolio final fichas de producto y oportunidades
Portafolio final fichas de producto y oportunidadesPortafolio final fichas de producto y oportunidades
Portafolio final fichas de producto y oportunidadesdaves01
 
Model arcs (J. Keller)
Model arcs (J. Keller)Model arcs (J. Keller)
Model arcs (J. Keller)fizah1212
 
Professional Persona Project: GANA
Professional Persona Project: GANAProfessional Persona Project: GANA
Professional Persona Project: GANAArs Magna
 

Viewers also liked (20)

Media Analysis of film opening: Media Language
Media Analysis of film opening: Media LanguageMedia Analysis of film opening: Media Language
Media Analysis of film opening: Media Language
 
Restaurant floor manager kpi
Restaurant floor manager kpiRestaurant floor manager kpi
Restaurant floor manager kpi
 
Project associate
Project associateProject associate
Project associate
 
Custom-Soft review system pune India
Custom-Soft review system pune IndiaCustom-Soft review system pune India
Custom-Soft review system pune India
 
Disastermanagementppt 130128141146-phpapp02
Disastermanagementppt 130128141146-phpapp02Disastermanagementppt 130128141146-phpapp02
Disastermanagementppt 130128141146-phpapp02
 
Ark PC brochure
Ark PC brochureArk PC brochure
Ark PC brochure
 
1С-Битрикс "Разумная разработка интернет-магазина: функционал и сценарии работы"
1С-Битрикс "Разумная разработка интернет-магазина: функционал и сценарии работы"1С-Битрикс "Разумная разработка интернет-магазина: функционал и сценарии работы"
1С-Битрикс "Разумная разработка интернет-магазина: функционал и сценарии работы"
 
Tik Bab 1 kelas 9
Tik Bab 1 kelas 9Tik Bab 1 kelas 9
Tik Bab 1 kelas 9
 
Presentación1 some any
Presentación1 some anyPresentación1 some any
Presentación1 some any
 
How to make kids grow taller
How to make kids grow tallerHow to make kids grow taller
How to make kids grow taller
 
Consumer protection act 1986 akosha
Consumer protection act 1986  akoshaConsumer protection act 1986  akosha
Consumer protection act 1986 akosha
 
Swede powerpoint
Swede powerpointSwede powerpoint
Swede powerpoint
 
Rupicon 2014 useful design patterns in rails
Rupicon 2014 useful design patterns in railsRupicon 2014 useful design patterns in rails
Rupicon 2014 useful design patterns in rails
 
活動紹介2014ホームページ用
活動紹介2014ホームページ用活動紹介2014ホームページ用
活動紹介2014ホームページ用
 
Portafolio final fichas de producto y oportunidades
Portafolio final fichas de producto y oportunidadesPortafolio final fichas de producto y oportunidades
Portafolio final fichas de producto y oportunidades
 
Www.hotroddingsingles.com
Www.hotroddingsingles.comWww.hotroddingsingles.com
Www.hotroddingsingles.com
 
Jobs and classroom objects
Jobs and classroom objectsJobs and classroom objects
Jobs and classroom objects
 
Model arcs (J. Keller)
Model arcs (J. Keller)Model arcs (J. Keller)
Model arcs (J. Keller)
 
Teoria de redes
Teoria de redesTeoria de redes
Teoria de redes
 
Professional Persona Project: GANA
Professional Persona Project: GANAProfessional Persona Project: GANA
Professional Persona Project: GANA
 

Similar to RSpec matchers

Metaprogramovanie #1
Metaprogramovanie #1Metaprogramovanie #1
Metaprogramovanie #1Jano Suchal
 
(Greach 2015) Dsl'ing your Groovy
(Greach 2015) Dsl'ing your Groovy(Greach 2015) Dsl'ing your Groovy
(Greach 2015) Dsl'ing your GroovyAlonso Torres
 
RubyEnRails2007 - Dr Nic Williams - DIY Syntax
RubyEnRails2007 - Dr Nic Williams - DIY SyntaxRubyEnRails2007 - Dr Nic Williams - DIY Syntax
RubyEnRails2007 - Dr Nic Williams - DIY SyntaxDr Nic Williams
 
Better rspec 進擊的 RSpec
Better rspec 進擊的 RSpecBetter rspec 進擊的 RSpec
Better rspec 進擊的 RSpecLi Hsuan Hung
 
OPM Recipe designer notes
OPM Recipe designer notesOPM Recipe designer notes
OPM Recipe designer notested-xu
 
Testing Ruby with Rspec (a beginner's guide)
Testing Ruby with Rspec (a beginner's guide)Testing Ruby with Rspec (a beginner's guide)
Testing Ruby with Rspec (a beginner's guide)Vysakh Sreenivasan
 
tree-sitter-objc-slides.pptx
tree-sitter-objc-slides.pptxtree-sitter-objc-slides.pptx
tree-sitter-objc-slides.pptxJiyee Sheng
 
Object oriented programming with python
Object oriented programming with pythonObject oriented programming with python
Object oriented programming with pythonArslan Arshad
 
MiamiJS - The Future of JavaScript
MiamiJS - The Future of JavaScriptMiamiJS - The Future of JavaScript
MiamiJS - The Future of JavaScriptCaridy Patino
 
Indexing documents
Indexing documentsIndexing documents
Indexing documentsMongoDB
 
Hadoop Integration in Cassandra
Hadoop Integration in CassandraHadoop Integration in Cassandra
Hadoop Integration in CassandraJairam Chandar
 
Hello- I hope you are doing well- I am doing my project- which is Rans (1).pdf
Hello- I hope you are doing well- I am doing my project- which is Rans (1).pdfHello- I hope you are doing well- I am doing my project- which is Rans (1).pdf
Hello- I hope you are doing well- I am doing my project- which is Rans (1).pdfIan0J2Bondo
 
Reproducibility with R
Reproducibility with RReproducibility with R
Reproducibility with RMartin Jung
 
Introduction to ad-3.4, an automatic differentiation library in Haskell
Introduction to ad-3.4, an automatic differentiation library in HaskellIntroduction to ad-3.4, an automatic differentiation library in Haskell
Introduction to ad-3.4, an automatic differentiation library in Haskellnebuta
 
Introduction to ad-3.4, an automatic differentiation library in Haskell
Introduction to ad-3.4, an automatic differentiation library in HaskellIntroduction to ad-3.4, an automatic differentiation library in Haskell
Introduction to ad-3.4, an automatic differentiation library in Haskellnebuta
 
Cascading Through Hadoop for the Boulder JUG
Cascading Through Hadoop for the Boulder JUGCascading Through Hadoop for the Boulder JUG
Cascading Through Hadoop for the Boulder JUGMatthew McCullough
 
PowerShell_LangRef_v3 (1).pdf
PowerShell_LangRef_v3 (1).pdfPowerShell_LangRef_v3 (1).pdf
PowerShell_LangRef_v3 (1).pdfoutcast96
 

Similar to RSpec matchers (20)

Metaprogramovanie #1
Metaprogramovanie #1Metaprogramovanie #1
Metaprogramovanie #1
 
(Greach 2015) Dsl'ing your Groovy
(Greach 2015) Dsl'ing your Groovy(Greach 2015) Dsl'ing your Groovy
(Greach 2015) Dsl'ing your Groovy
 
RubyEnRails2007 - Dr Nic Williams - DIY Syntax
RubyEnRails2007 - Dr Nic Williams - DIY SyntaxRubyEnRails2007 - Dr Nic Williams - DIY Syntax
RubyEnRails2007 - Dr Nic Williams - DIY Syntax
 
Better rspec 進擊的 RSpec
Better rspec 進擊的 RSpecBetter rspec 進擊的 RSpec
Better rspec 進擊的 RSpec
 
OPM Recipe designer notes
OPM Recipe designer notesOPM Recipe designer notes
OPM Recipe designer notes
 
Testing Ruby with Rspec (a beginner's guide)
Testing Ruby with Rspec (a beginner's guide)Testing Ruby with Rspec (a beginner's guide)
Testing Ruby with Rspec (a beginner's guide)
 
tree-sitter-objc-slides.pptx
tree-sitter-objc-slides.pptxtree-sitter-objc-slides.pptx
tree-sitter-objc-slides.pptx
 
Object oriented programming with python
Object oriented programming with pythonObject oriented programming with python
Object oriented programming with python
 
Tuples All the Way Down
Tuples All the Way DownTuples All the Way Down
Tuples All the Way Down
 
MiamiJS - The Future of JavaScript
MiamiJS - The Future of JavaScriptMiamiJS - The Future of JavaScript
MiamiJS - The Future of JavaScript
 
Indexing documents
Indexing documentsIndexing documents
Indexing documents
 
Why ruby
Why rubyWhy ruby
Why ruby
 
Hadoop Integration in Cassandra
Hadoop Integration in CassandraHadoop Integration in Cassandra
Hadoop Integration in Cassandra
 
Hello- I hope you are doing well- I am doing my project- which is Rans (1).pdf
Hello- I hope you are doing well- I am doing my project- which is Rans (1).pdfHello- I hope you are doing well- I am doing my project- which is Rans (1).pdf
Hello- I hope you are doing well- I am doing my project- which is Rans (1).pdf
 
Metaprogramming
MetaprogrammingMetaprogramming
Metaprogramming
 
Reproducibility with R
Reproducibility with RReproducibility with R
Reproducibility with R
 
Introduction to ad-3.4, an automatic differentiation library in Haskell
Introduction to ad-3.4, an automatic differentiation library in HaskellIntroduction to ad-3.4, an automatic differentiation library in Haskell
Introduction to ad-3.4, an automatic differentiation library in Haskell
 
Introduction to ad-3.4, an automatic differentiation library in Haskell
Introduction to ad-3.4, an automatic differentiation library in HaskellIntroduction to ad-3.4, an automatic differentiation library in Haskell
Introduction to ad-3.4, an automatic differentiation library in Haskell
 
Cascading Through Hadoop for the Boulder JUG
Cascading Through Hadoop for the Boulder JUGCascading Through Hadoop for the Boulder JUG
Cascading Through Hadoop for the Boulder JUG
 
PowerShell_LangRef_v3 (1).pdf
PowerShell_LangRef_v3 (1).pdfPowerShell_LangRef_v3 (1).pdf
PowerShell_LangRef_v3 (1).pdf
 

More from rupicon

DIY Cartography
DIY CartographyDIY Cartography
DIY Cartographyrupicon
 
Dr. PostGIS or: How I Learned to Stop Worrying and Love the Docs
Dr. PostGIS or: How I Learned to Stop Worrying and Love the DocsDr. PostGIS or: How I Learned to Stop Worrying and Love the Docs
Dr. PostGIS or: How I Learned to Stop Worrying and Love the Docsrupicon
 
Are you tougher than a boy/girl scout?
Are you tougher than a boy/girl scout?Are you tougher than a boy/girl scout?
Are you tougher than a boy/girl scout?rupicon
 
Johnny Cache
Johnny CacheJohnny Cache
Johnny Cacherupicon
 
U wont bleev wut dis code doez
U wont bleev wut dis code doezU wont bleev wut dis code doez
U wont bleev wut dis code doezrupicon
 
Rupicon 2014 Action pack
Rupicon 2014 Action packRupicon 2014 Action pack
Rupicon 2014 Action packrupicon
 
Rupicon 2014 Single table inheritance
Rupicon 2014 Single table inheritanceRupicon 2014 Single table inheritance
Rupicon 2014 Single table inheritancerupicon
 
Rupicon 2014 solid
Rupicon 2014 solidRupicon 2014 solid
Rupicon 2014 solidrupicon
 
Rupicon 2014 caching
Rupicon 2014 cachingRupicon 2014 caching
Rupicon 2014 cachingrupicon
 

More from rupicon (9)

DIY Cartography
DIY CartographyDIY Cartography
DIY Cartography
 
Dr. PostGIS or: How I Learned to Stop Worrying and Love the Docs
Dr. PostGIS or: How I Learned to Stop Worrying and Love the DocsDr. PostGIS or: How I Learned to Stop Worrying and Love the Docs
Dr. PostGIS or: How I Learned to Stop Worrying and Love the Docs
 
Are you tougher than a boy/girl scout?
Are you tougher than a boy/girl scout?Are you tougher than a boy/girl scout?
Are you tougher than a boy/girl scout?
 
Johnny Cache
Johnny CacheJohnny Cache
Johnny Cache
 
U wont bleev wut dis code doez
U wont bleev wut dis code doezU wont bleev wut dis code doez
U wont bleev wut dis code doez
 
Rupicon 2014 Action pack
Rupicon 2014 Action packRupicon 2014 Action pack
Rupicon 2014 Action pack
 
Rupicon 2014 Single table inheritance
Rupicon 2014 Single table inheritanceRupicon 2014 Single table inheritance
Rupicon 2014 Single table inheritance
 
Rupicon 2014 solid
Rupicon 2014 solidRupicon 2014 solid
Rupicon 2014 solid
 
Rupicon 2014 caching
Rupicon 2014 cachingRupicon 2014 caching
Rupicon 2014 caching
 

Recently uploaded

Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
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
 
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
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionSolGuruz
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
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
 
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.
 
Clustering techniques data mining book ....
Clustering techniques data mining book ....Clustering techniques data mining book ....
Clustering techniques data mining book ....ShaimaaMohamedGalal
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 
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
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️Delhi Call girls
 
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
 
Test Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendTest Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendArshad QA
 
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
 
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
 

Recently uploaded (20)

Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
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-...
 
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 
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
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
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
 
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 ...
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
Clustering techniques data mining book ....
Clustering techniques data mining book ....Clustering techniques data mining book ....
Clustering techniques data mining book ....
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 
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
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
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 ...
 
Test Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendTest Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and Backend
 
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
 
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
 

RSpec matchers

  • 1. rspec matchers Zaharie Marius - 06-03-2015 1 / 9
  • 3. Aliases RSpec 3 provides one or more aliases for all the built-in matchers. consistent phrasing ("a_[type of object][verb]ing") so they are easy to guess: a_string_starting_withfor start_with a_string_includinga_collection_includinga_hash_includingaliases of include see a list of them in this gist easier to read when used in compound expresions or composed matchers and also more readable failure mssages. RSpec 3 made it easy to define an alias for some built-in matcher or even your custom matchers. Here is the bit of code to define the a_string_starting_with alias of start_with: RSpec::Matchers.alias_matcher:a_string_starting_with,:start_with 3 / 9
  • 4. What are these composable matchers good for? They will save you from this ... describe"GET/api/areas/:area_id/pscs"do context"whengivenvaliddata"do it"returnsthePSCSforgivenareainJSON"do get"/api/areas/#{area.id}/pscs", {access_token:access_token_for(user),level_id:area.default_level.id}, {'Accept'=>Mime::JSON} expect(response.status).tobe(200) expect(response.content_type).tobe(Mime::JSON) json_response=json(response.body) expect(json_response[:latitude]).to eq(area.location.point.latitude.to_f) expect(json_response[:longitude]).to eq(area.location.point.longitude.to_f) #otherlongexpectshere expect(level_node[:previous_level][:level_id]).toeq(area.parkings_levels.order_by_lev expect(level_node[:image][:url]).to eq(area.level_image(area.default_leve pscs_latitudes=json_response[:pscs].map{|e|e[:pscs][:latitude]} expect(pscs_latitudes).toinclude(area.pscs_on_level(area.default_level.id).first.poin end end end 4 / 9
  • 5. The solution is to use the matchmatcher, which became in rspec 3 a kind of black hole for any rspec matcher. describe"GET/api/areas/:area_id/pscs"do context"whengivenvaliddata"do it"returnsthePSCSforgivenareainJSON"do get"/api/areas/#{area.id}/pscs", {level_id:area.default_level.id}, { 'Authorization'=>"Bearer#{access_token_for(user)}", 'Accept'=>Mime::JSON } expect(response).tohave_status(200).and_content_type(Mime::JSON) json_response=json(response.body) expect(json_response).tomatch(pscs_list_composed_matcher(area:area)) expect(json_response[:pscs]).tocontain_latitude(area.pscs_on_level(area.default_level end end end 5 / 9
  • 6. The object passed to matchis more like a big hash containing any rspec matchers as values for his keys: modulePscsHelpers defpscs_list_composed_matcher(area:,current_level:nil,is_favorite:false) current_level=area.default_level { latitude:area.location.point.latitude.to_f, longitude:area.location.point.longitude.to_f, is_favorite:is_favorite, zoomLevel:(a_value>0), level:current_level_matcher(area,current_level), pscs:an_instance_of(Array) } end defcurrent_level_matcher(area,current_level) { level_id:current_level.id, name:current_level.name, default_level:level_matcher(area.default_level), next_level: level_matcher(area.levels.first), previous_level:level_matcher(area.levels.last), image:level_image_matcher(area,current_level) } end #reusable deflevel_matcher(level) #... end deflevel_image_matcher(area,current_level) #... 6 / 9
  • 7. 2. Custom matchers 2.1 How to: RSpec::Matchers.define:contain_latitudedo|expected| latitudes=[] matchdo|actual| latitudes=actual.collect{|item|item[:pscs][:latitude]} latitudes.find{|lat|lat.to_s==expected.to_s} end failure_messagedo|actual| "expectedthatpscs_listwithlatitudesn #{latitudes}nwouldcontainthe'#{expec end end #anduseitlikethis: expect(json_response[:pscs]).tocontain_latitude(45.4545) #orusingacompoundexpression expect(json_response[:pscs]) .tocontain_latitude(45.4545) .andcontain_longitude(25.90) 7 / 9
  • 8. 2.2 Chained matchers with fluent interface When you want something more expressive then .andor .orfrom previous example modulePscsHelpers #scopedmatcherswiththePscsHelpersmodule extendRSpec::Matchers::DSL matcher:contain_a_latitude_bigger_thando|first| latitudes=[] matchdo|actual| latitudes=actual.collect{|item|item[:pscs][:latitude]} bigger=latitudes.find{|lat|lat>expected} smaller=latitudes.find{|lat|lat<second} bigger&&smaller end chain:but_smaller_thando|second| @second=second end end end #andthefancyexpectationusingit expect(response).tocontain_a_latitude_bigger_than(43).but_smaller_than(47) 8 / 9
  • 9. Resources RSpec 3 - Composable Matchers List of RSpec 3 Aliases gist Define Matcher 9 / 9