SlideShare a Scribd company logo
1 of 10
Download to read offline
RSpec
i
AbouttheTutorial
RSpec is a unit test framework for the Ruby programming language. RSpec is different
than traditional xUnit frameworks like JUnit because RSpec is a Behavior driven
development tool. What this means is that, tests written in RSpec focus on the "behavior"
of an application being tested. RSpec does not put emphasis on, how the application works
but instead on how it behaves, in other words, what the application actually does.
This tutorial will show you, how to use RSpec to test your code when building applications
with Ruby.
Audience
This tutorial is for beginners who want to learn how to write better code in Ruby. After
finishing this tutorial, you will be able to incorporate RSpec tests into your daily coding
practices.
Prerequisites
In order to benefit from reading this tutorial, you should have some experience with
programming, specifically with Ruby.
Disclaimer&Copyright
 Copyright 2015 by Tutorials Point (I) Pvt. Ltd.
All the content and graphics published in this e-book are the property of Tutorials Point (I)
Pvt. Ltd. The user of this e-book is prohibited to reuse, retain, copy, distribute, or republish
any contents or a part of contents of this e-book in any manner without written consent
of the publisher.
We strive to update the contents of our website and tutorials as timely and as precisely as
possible, however, the contents may contain inaccuracies or errors. Tutorials Point (I) Pvt.
Ltd. provides no guarantee regarding the accuracy, timeliness, or completeness of our
website or its contents including this tutorial. If you discover any errors on our website or
in this tutorial, please notify us at contact@tutorialspoint.com
RSpec
ii
TableofContents
About the Tutorial ............................................................................................................................................i
Audience...........................................................................................................................................................i
Prerequisites.....................................................................................................................................................i
Disclaimer & Copyright .....................................................................................................................................i
Table of Contents.............................................................................................................................................ii
1. RSPEC – INTRODUCTION ......................................................................................................1
RSpec Environment..........................................................................................................................................1
2. RSPEC – BASIC SYNTAX.........................................................................................................4
The describe Keyword .....................................................................................................................................4
The context Keyword.......................................................................................................................................4
The it Keyword ................................................................................................................................................5
The expect Keyword ........................................................................................................................................5
3. RSPEC – WRITING SPECS ......................................................................................................6
4. RSPEC – MATCHERS ...........................................................................................................11
Equality/Identity Matchers............................................................................................................................11
Comparison Matchers....................................................................................................................................12
Class/Type Matchers .....................................................................................................................................13
True/False/Nil Matchers................................................................................................................................14
Error Matchers...............................................................................................................................................15
5. RSPEC – TEST DOUBLES......................................................................................................17
6. RSPEC – STUBS...................................................................................................................19
7. RSPEC – HOOKS..................................................................................................................22
8. RSPEC – TAGS.....................................................................................................................25
RSpec
iii
9. RSPEC – SUBJECTS..............................................................................................................26
10. RSPEC – HELPERS............................................................................................................28
11. RSPEC – METADATA........................................................................................................30
12. RSPEC – FILTERING..........................................................................................................33
RSpec Formatters ..........................................................................................................................................34
Failed Examples .............................................................................................................................................37
13. RSPEC – EXPECTATIONS ..................................................................................................38
RSpec
1
RSpec is a unit test framework for the Ruby programming language. RSpec is different
than traditional xUnit frameworks like JUnit because RSpec is a Behavior driven
development tool. What this means is that, tests written in RSpec focus on the “behavior”
of an application being tested. RSpec does not put emphasis on, how the application works
but instead on how it behaves, in other words, what the application actually does.
RSpecEnvironment
First of all, you will need to install Ruby on your computer. However, if you haven’t already
done earlier, then you can download and install Ruby from the main Ruby website:
https://www.ruby-lang.org/en/documentation/installation.
If you are installing Ruby on Windows, you should have the Ruby installer for Windows
here at: http://www.rubyinstaller.org
For this tutorial, you will only need text editor, such as Notepad and a command line
console. The examples here will use cmd.exe on Windows.
To run cmd.exe, simply click on the Start menu and type “cmd.exe”, then hit the Return
key.
At the command prompt in your cmd.exe window, type the following command to see
what version of Ruby you are using:
ruby -v
You should see the below output that looks similar to this:
ruby 2.2.3p173 (2015-08-18 revision 51636) [x64-mingw32]
The examples in this tutorial will use Ruby 2.2.3 but any version of Ruby higher than 2.0.0
will suffice. Next, we need to install the RSpec gem for your Ruby installation. A gem is
a Ruby library which you can use in your own code. In order to install a gem, you need
to use the gem command.
Let’s install the Rspec gem now. Go back to your cmd.exe Window and type the following:
gem install rspec
You should have a list of dependent gems that were installed, these are gems that the
rspec gem needs to function correctly. At the end of the output, you should see something
that looks like this:
Done installing documentation for diff-lcs, rspec-support, rspec-mocks, rspec-
expectations, rspec-core, rspec after 22 seconds
6 gems installed
1. RSpec – Introduction
RSpec
2
Do not worry, if your output does not look exactly the same. Also, if you are using a Mac
or Linux computer, you may need to either run gem install rspec command using sudo
or use a tool like HomeBrew or RVM to install the rspec gem.
Hello World
To get started, let’s create a directory (folder) to store our RSpec files. In your cmd.exe
window, type the following:
cd 
Then type:
mkdir rspec_tutorial
And finally, type:
cd rspec_tutorial
From here, we’re going to create another directory named spec, do that by typing:
mkdir spec
We are going to store our RSpec files in this folder. RSpec files are known as “specs”. If
this seems confusing to you, you can think of a spec file as a test file. RSpec uses the
term “spec” which is a short form for “specification”.
Since, RSpec is a BDD test tool, the goal is to focus on what the application does and
whether or not it follows a specification. In behavior driven development, the specification
is often described in terms of a “User Story”. RSpec is designed to make it clear whether
the target code is behaving correctly, in other words following the specification.
Let’s return to our Hello World code. Open a text editor and add the following code:
class HelloWorld
def say_hello
"Hello World!"
end
end
describe HelloWorld do
context “When testing the HelloWorld class” do
it "should say 'Hello World' when we call the say_hello method" do
hw = HelloWorld.new
message = hw.say_hello
expect(message).to eq "Hello World!"
end
end
RSpec
3
end
Next, save this to a file named hello_world_spec.rb in the spec folder that you created
above. Now back in your cmd.exe window, run this command:
rspec spec spechello_world_spec.rb
When the command completes, you should see output that looks like this:
Finished in 0.002 seconds (files took 0.11101 seconds to load)
1 example, 0 failures
Congratulations, you just created and ran your first RSpec unit test!
In the next section, we will continue to discuss the syntax of RSpec files.
RSpec
4
Let’s take a closer look at the code of our HelloWorld example. First of all, in case it isn’t
clear, we are testing the functionality of the HelloWorld class. This of course, is a very
simple class that contains only one method say_hello().
Here is the RSpec code again:
describe HelloWorld do
context “When testing the HelloWorld class” do
it "The say_hello method should return 'Hello World'" do
hw = HelloWorld.new
message = hw.say_hello
expect(message).to eq "Hello World!"
end
end
end
ThedescribeKeyword
The word describe is an RSpec keyword. It is used to define an “Example Group”. You
can think of an “Example Group” as a collection of tests. The describe keyword can take
a class name and/or string argument. You also need to pass a block argument to
describe, this will contain the individual tests, or as they are known in RSpec, the
“Examples”. The block is just a Ruby block designated by the Ruby do/end keywords
ThecontextKeyword
The context keyword is similar to describe. It too can accept a class name and/or string
argument. You should use a block with context as well. The idea of context is that it
encloses tests of a certain type.
For example, you can specify groups of Examples with different contexts like this:
context “When passing bad parameters to the foobar() method”
context “When passing valid parameters to the foobar() method”
context “When testing corner cases with the foobar() method”
The context keyword is not mandatory, but it helps to add more details about the
examples that it contains.
2. RSpec – Basic Syntax
RSpec
5
TheitKeyword
The word it is another RSpec keyword which is used to define an “Example”. An example
is basically a test or a test case. Again, like describe and context, it accepts both class
name and string arguments and should be used with a block argument, designated with
do/end. In the case of it, it is customary to only pass a string and block argument. The
string argument often uses the word “should” and is meant to describe what specific
behavior should happen inside the it block. In other words, it describes that expected
outcome is for the Example.
Note the it block from our HelloWorld Example:
it "The say_hello method should return 'Hello World'" do
The string makes it clear what should happen when we call say hello on an instance of the
HelloWorld class. This part of the RSpec philosophy, an Example is not just a test, it’s also
a specification (a spec). In other words, an Example both documents and tests the
expected behavior of your Ruby code.
TheexpectKeyword
The expect keyword is used to define an “Expectation” in RSpec. This is a verification
step where we check, that a specific expected condition has been met.
From our HelloWorld Example, we have:
expect(message).to eql "Hello World!"
The idea with expect statements is that they read like normal English. You can say this
aloud as “Expect the variable message to equal the string ‘Hello World’”. The idea is that
its descriptive and also easy to read, even for non-technical stakeholders such as project
managers.
The to keyword
The to keyword is used as part of expect statements. Note that you can also use the
not_to keyword to express the opposite, when you want the Expectation to be false. You
can see that to is used with a dot, expect(message).to, because it actually just a regular
Ruby method. In fact, all of the RSpec keywords are really just Ruby methods.
The eql keyword
The eql keyword is a special RSpec keyword called a Matcher. You use Matchers to specify
what type of condition you are testing to be true (or false).
In our HelloWorld expect statement, it is clear that eql means string equality. Note that,
there are different types of equality operators in Ruby and consequently different
corresponding Matchers in RSpec. We will explore the many different types of Matchers
in a later section.
RSpec
6
End of ebook preview
If you liked what you saw…
Buy it from our store @ https://store.tutorialspoint.com

More Related Content

Similar to Rspec tutorial

BDD style Unit Testing
BDD style Unit TestingBDD style Unit Testing
BDD style Unit Testing
Wen-Tien Chang
 
A little-book-of-r-for-time-series
A little-book-of-r-for-time-seriesA little-book-of-r-for-time-series
A little-book-of-r-for-time-series
S DG
 
From Ant to Rake
From Ant to RakeFrom Ant to Rake
From Ant to Rake
jazzman1980
 

Similar to Rspec tutorial (20)

RSpec 3.0: Under the Covers
RSpec 3.0: Under the CoversRSpec 3.0: Under the Covers
RSpec 3.0: Under the Covers
 
R tutorial
R tutorialR tutorial
R tutorial
 
DEF CON 27 - workshop - ISAAC EVANS - discover exploit and eradicate entire v...
DEF CON 27 - workshop - ISAAC EVANS - discover exploit and eradicate entire v...DEF CON 27 - workshop - ISAAC EVANS - discover exploit and eradicate entire v...
DEF CON 27 - workshop - ISAAC EVANS - discover exploit and eradicate entire v...
 
TDD, BDD, RSpec
TDD, BDD, RSpecTDD, BDD, RSpec
TDD, BDD, RSpec
 
Pyspark tutorial
Pyspark tutorialPyspark tutorial
Pyspark tutorial
 
Pyspark tutorial
Pyspark tutorialPyspark tutorial
Pyspark tutorial
 
99 Apache Spark interview questions for professionals - https://www.amazon.co...
99 Apache Spark interview questions for professionals - https://www.amazon.co...99 Apache Spark interview questions for professionals - https://www.amazon.co...
99 Apache Spark interview questions for professionals - https://www.amazon.co...
 
FGCU Camp Talk
FGCU Camp TalkFGCU Camp Talk
FGCU Camp Talk
 
BDD style Unit Testing
BDD style Unit TestingBDD style Unit Testing
BDD style Unit Testing
 
A little-book-of-r-for-time-series
A little-book-of-r-for-time-seriesA little-book-of-r-for-time-series
A little-book-of-r-for-time-series
 
Cross-platform Desktop Apps development using HTML, CSS, JS with Electron
Cross-platform Desktop Apps development using HTML, CSS, JS with ElectronCross-platform Desktop Apps development using HTML, CSS, JS with Electron
Cross-platform Desktop Apps development using HTML, CSS, JS with Electron
 
Behavioural Testing Ruby/Rails Apps @ Scale - Rspec & Cucumber
       Behavioural Testing Ruby/Rails Apps @ Scale - Rspec & Cucumber       Behavioural Testing Ruby/Rails Apps @ Scale - Rspec & Cucumber
Behavioural Testing Ruby/Rails Apps @ Scale - Rspec & Cucumber
 
salesforce_apex_developer_guide
salesforce_apex_developer_guidesalesforce_apex_developer_guide
salesforce_apex_developer_guide
 
TypeScipt - Get Started
TypeScipt - Get StartedTypeScipt - Get Started
TypeScipt - Get Started
 
From Ant to Rake
From Ant to RakeFrom Ant to Rake
From Ant to Rake
 
rails_tutorial
rails_tutorialrails_tutorial
rails_tutorial
 
rails_tutorial
rails_tutorialrails_tutorial
rails_tutorial
 
Dev streams2
Dev streams2Dev streams2
Dev streams2
 
Deploying your rails application to a clean ubuntu 10
Deploying your rails application to a clean ubuntu 10Deploying your rails application to a clean ubuntu 10
Deploying your rails application to a clean ubuntu 10
 
Rspec basics
Rspec basicsRspec basics
Rspec basics
 

More from HarikaReddy115

More from HarikaReddy115 (20)

Dbms tutorial
Dbms tutorialDbms tutorial
Dbms tutorial
 
Data structures algorithms_tutorial
Data structures algorithms_tutorialData structures algorithms_tutorial
Data structures algorithms_tutorial
 
Wireless communication tutorial
Wireless communication tutorialWireless communication tutorial
Wireless communication tutorial
 
Cryptography tutorial
Cryptography tutorialCryptography tutorial
Cryptography tutorial
 
Cosmology tutorial
Cosmology tutorialCosmology tutorial
Cosmology tutorial
 
Control systems tutorial
Control systems tutorialControl systems tutorial
Control systems tutorial
 
Computer logical organization_tutorial
Computer logical organization_tutorialComputer logical organization_tutorial
Computer logical organization_tutorial
 
Computer fundamentals tutorial
Computer fundamentals tutorialComputer fundamentals tutorial
Computer fundamentals tutorial
 
Compiler design tutorial
Compiler design tutorialCompiler design tutorial
Compiler design tutorial
 
Communication technologies tutorial
Communication technologies tutorialCommunication technologies tutorial
Communication technologies tutorial
 
Biometrics tutorial
Biometrics tutorialBiometrics tutorial
Biometrics tutorial
 
Behavior driven development_tutorial
Behavior driven development_tutorialBehavior driven development_tutorial
Behavior driven development_tutorial
 
Basics of computers_tutorial
Basics of computers_tutorialBasics of computers_tutorial
Basics of computers_tutorial
 
Basics of computer_science_tutorial
Basics of computer_science_tutorialBasics of computer_science_tutorial
Basics of computer_science_tutorial
 
Basic electronics tutorial
Basic electronics tutorialBasic electronics tutorial
Basic electronics tutorial
 
Auditing tutorial
Auditing tutorialAuditing tutorial
Auditing tutorial
 
Artificial neural network_tutorial
Artificial neural network_tutorialArtificial neural network_tutorial
Artificial neural network_tutorial
 
Artificial intelligence tutorial
Artificial intelligence tutorialArtificial intelligence tutorial
Artificial intelligence tutorial
 
Antenna theory tutorial
Antenna theory tutorialAntenna theory tutorial
Antenna theory tutorial
 
Analog communication tutorial
Analog communication tutorialAnalog communication tutorial
Analog communication tutorial
 

Recently uploaded

Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
fonyou31
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
QucHHunhnh
 

Recently uploaded (20)

INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdf
 
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 

Rspec tutorial

  • 1.
  • 2. RSpec i AbouttheTutorial RSpec is a unit test framework for the Ruby programming language. RSpec is different than traditional xUnit frameworks like JUnit because RSpec is a Behavior driven development tool. What this means is that, tests written in RSpec focus on the "behavior" of an application being tested. RSpec does not put emphasis on, how the application works but instead on how it behaves, in other words, what the application actually does. This tutorial will show you, how to use RSpec to test your code when building applications with Ruby. Audience This tutorial is for beginners who want to learn how to write better code in Ruby. After finishing this tutorial, you will be able to incorporate RSpec tests into your daily coding practices. Prerequisites In order to benefit from reading this tutorial, you should have some experience with programming, specifically with Ruby. Disclaimer&Copyright  Copyright 2015 by Tutorials Point (I) Pvt. Ltd. All the content and graphics published in this e-book are the property of Tutorials Point (I) Pvt. Ltd. The user of this e-book is prohibited to reuse, retain, copy, distribute, or republish any contents or a part of contents of this e-book in any manner without written consent of the publisher. We strive to update the contents of our website and tutorials as timely and as precisely as possible, however, the contents may contain inaccuracies or errors. Tutorials Point (I) Pvt. Ltd. provides no guarantee regarding the accuracy, timeliness, or completeness of our website or its contents including this tutorial. If you discover any errors on our website or in this tutorial, please notify us at contact@tutorialspoint.com
  • 3. RSpec ii TableofContents About the Tutorial ............................................................................................................................................i Audience...........................................................................................................................................................i Prerequisites.....................................................................................................................................................i Disclaimer & Copyright .....................................................................................................................................i Table of Contents.............................................................................................................................................ii 1. RSPEC – INTRODUCTION ......................................................................................................1 RSpec Environment..........................................................................................................................................1 2. RSPEC – BASIC SYNTAX.........................................................................................................4 The describe Keyword .....................................................................................................................................4 The context Keyword.......................................................................................................................................4 The it Keyword ................................................................................................................................................5 The expect Keyword ........................................................................................................................................5 3. RSPEC – WRITING SPECS ......................................................................................................6 4. RSPEC – MATCHERS ...........................................................................................................11 Equality/Identity Matchers............................................................................................................................11 Comparison Matchers....................................................................................................................................12 Class/Type Matchers .....................................................................................................................................13 True/False/Nil Matchers................................................................................................................................14 Error Matchers...............................................................................................................................................15 5. RSPEC – TEST DOUBLES......................................................................................................17 6. RSPEC – STUBS...................................................................................................................19 7. RSPEC – HOOKS..................................................................................................................22 8. RSPEC – TAGS.....................................................................................................................25
  • 4. RSpec iii 9. RSPEC – SUBJECTS..............................................................................................................26 10. RSPEC – HELPERS............................................................................................................28 11. RSPEC – METADATA........................................................................................................30 12. RSPEC – FILTERING..........................................................................................................33 RSpec Formatters ..........................................................................................................................................34 Failed Examples .............................................................................................................................................37 13. RSPEC – EXPECTATIONS ..................................................................................................38
  • 5. RSpec 1 RSpec is a unit test framework for the Ruby programming language. RSpec is different than traditional xUnit frameworks like JUnit because RSpec is a Behavior driven development tool. What this means is that, tests written in RSpec focus on the “behavior” of an application being tested. RSpec does not put emphasis on, how the application works but instead on how it behaves, in other words, what the application actually does. RSpecEnvironment First of all, you will need to install Ruby on your computer. However, if you haven’t already done earlier, then you can download and install Ruby from the main Ruby website: https://www.ruby-lang.org/en/documentation/installation. If you are installing Ruby on Windows, you should have the Ruby installer for Windows here at: http://www.rubyinstaller.org For this tutorial, you will only need text editor, such as Notepad and a command line console. The examples here will use cmd.exe on Windows. To run cmd.exe, simply click on the Start menu and type “cmd.exe”, then hit the Return key. At the command prompt in your cmd.exe window, type the following command to see what version of Ruby you are using: ruby -v You should see the below output that looks similar to this: ruby 2.2.3p173 (2015-08-18 revision 51636) [x64-mingw32] The examples in this tutorial will use Ruby 2.2.3 but any version of Ruby higher than 2.0.0 will suffice. Next, we need to install the RSpec gem for your Ruby installation. A gem is a Ruby library which you can use in your own code. In order to install a gem, you need to use the gem command. Let’s install the Rspec gem now. Go back to your cmd.exe Window and type the following: gem install rspec You should have a list of dependent gems that were installed, these are gems that the rspec gem needs to function correctly. At the end of the output, you should see something that looks like this: Done installing documentation for diff-lcs, rspec-support, rspec-mocks, rspec- expectations, rspec-core, rspec after 22 seconds 6 gems installed 1. RSpec – Introduction
  • 6. RSpec 2 Do not worry, if your output does not look exactly the same. Also, if you are using a Mac or Linux computer, you may need to either run gem install rspec command using sudo or use a tool like HomeBrew or RVM to install the rspec gem. Hello World To get started, let’s create a directory (folder) to store our RSpec files. In your cmd.exe window, type the following: cd Then type: mkdir rspec_tutorial And finally, type: cd rspec_tutorial From here, we’re going to create another directory named spec, do that by typing: mkdir spec We are going to store our RSpec files in this folder. RSpec files are known as “specs”. If this seems confusing to you, you can think of a spec file as a test file. RSpec uses the term “spec” which is a short form for “specification”. Since, RSpec is a BDD test tool, the goal is to focus on what the application does and whether or not it follows a specification. In behavior driven development, the specification is often described in terms of a “User Story”. RSpec is designed to make it clear whether the target code is behaving correctly, in other words following the specification. Let’s return to our Hello World code. Open a text editor and add the following code: class HelloWorld def say_hello "Hello World!" end end describe HelloWorld do context “When testing the HelloWorld class” do it "should say 'Hello World' when we call the say_hello method" do hw = HelloWorld.new message = hw.say_hello expect(message).to eq "Hello World!" end end
  • 7. RSpec 3 end Next, save this to a file named hello_world_spec.rb in the spec folder that you created above. Now back in your cmd.exe window, run this command: rspec spec spechello_world_spec.rb When the command completes, you should see output that looks like this: Finished in 0.002 seconds (files took 0.11101 seconds to load) 1 example, 0 failures Congratulations, you just created and ran your first RSpec unit test! In the next section, we will continue to discuss the syntax of RSpec files.
  • 8. RSpec 4 Let’s take a closer look at the code of our HelloWorld example. First of all, in case it isn’t clear, we are testing the functionality of the HelloWorld class. This of course, is a very simple class that contains only one method say_hello(). Here is the RSpec code again: describe HelloWorld do context “When testing the HelloWorld class” do it "The say_hello method should return 'Hello World'" do hw = HelloWorld.new message = hw.say_hello expect(message).to eq "Hello World!" end end end ThedescribeKeyword The word describe is an RSpec keyword. It is used to define an “Example Group”. You can think of an “Example Group” as a collection of tests. The describe keyword can take a class name and/or string argument. You also need to pass a block argument to describe, this will contain the individual tests, or as they are known in RSpec, the “Examples”. The block is just a Ruby block designated by the Ruby do/end keywords ThecontextKeyword The context keyword is similar to describe. It too can accept a class name and/or string argument. You should use a block with context as well. The idea of context is that it encloses tests of a certain type. For example, you can specify groups of Examples with different contexts like this: context “When passing bad parameters to the foobar() method” context “When passing valid parameters to the foobar() method” context “When testing corner cases with the foobar() method” The context keyword is not mandatory, but it helps to add more details about the examples that it contains. 2. RSpec – Basic Syntax
  • 9. RSpec 5 TheitKeyword The word it is another RSpec keyword which is used to define an “Example”. An example is basically a test or a test case. Again, like describe and context, it accepts both class name and string arguments and should be used with a block argument, designated with do/end. In the case of it, it is customary to only pass a string and block argument. The string argument often uses the word “should” and is meant to describe what specific behavior should happen inside the it block. In other words, it describes that expected outcome is for the Example. Note the it block from our HelloWorld Example: it "The say_hello method should return 'Hello World'" do The string makes it clear what should happen when we call say hello on an instance of the HelloWorld class. This part of the RSpec philosophy, an Example is not just a test, it’s also a specification (a spec). In other words, an Example both documents and tests the expected behavior of your Ruby code. TheexpectKeyword The expect keyword is used to define an “Expectation” in RSpec. This is a verification step where we check, that a specific expected condition has been met. From our HelloWorld Example, we have: expect(message).to eql "Hello World!" The idea with expect statements is that they read like normal English. You can say this aloud as “Expect the variable message to equal the string ‘Hello World’”. The idea is that its descriptive and also easy to read, even for non-technical stakeholders such as project managers. The to keyword The to keyword is used as part of expect statements. Note that you can also use the not_to keyword to express the opposite, when you want the Expectation to be false. You can see that to is used with a dot, expect(message).to, because it actually just a regular Ruby method. In fact, all of the RSpec keywords are really just Ruby methods. The eql keyword The eql keyword is a special RSpec keyword called a Matcher. You use Matchers to specify what type of condition you are testing to be true (or false). In our HelloWorld expect statement, it is clear that eql means string equality. Note that, there are different types of equality operators in Ruby and consequently different corresponding Matchers in RSpec. We will explore the many different types of Matchers in a later section.
  • 10. RSpec 6 End of ebook preview If you liked what you saw… Buy it from our store @ https://store.tutorialspoint.com