RSpec is a unit testing framework for Ruby that focuses on specifying and testing the behavior of code. The document introduces RSpec's basic syntax including the describe, context, it, expect, and matchers keywords. It provides an example "hello world" test to demonstrate setting up an RSpec file and running tests. The example specifies and tests that a HelloWorld class returns the string "Hello World" from its say_hello method.
How to implement ruby on rails testing practices to build a successful web ap...Katy Slemon
In this blog, we write on both the test-driven development and the behavior-driven development who are RoR testing practices to build a successful web application.
Rspec and Capybara Intro Tutorial at RailsConf 2013Brian Sam-Bodden
Behavior-Driven Development and Acceptance Testing are heavily intertwined and in many aspects are one and the same. Both focus on starting at the outer layers of your application by concentrating on what matter to users; behavior. In this session/workshop we'll talk about how testing can be used both for specifying your application yet to be develop expected behavior and as accurate, running documentation that can be used to validate your stakeholder's acceptance criteria. We'll talk about the different types of testing and do a few hands-on exercises to flesh out a Rails application with RSpec and Capybara.
Test driven development is a popular concept in software development, leading to higher quality code that’s easier to maintain. Automated testing is normally a foreign concept in the operations world, but as you ssh into your servers to make that quick fix or run your updated script (fingers crossed), you might be wondering if there’s a better way. A way that gives you the confidence in your script and lets you test those scripts in isolation. Well Arthur has good news for you, there is a better way! Test driven infrastructure (TDI) is now possible. He knows, it sounds crazy.
At this session you’ll learn the how, and more importantly the why, of TDI. You’ll see how Chef (or any other Config Management framework) can be tested with Test Kitchen and ServerSpec. You’ll also learn how to improve your feedback cycle with Docker, and using the Docker approach on a CI server. There may even be some live demos!
Finally, the Ops world collides with the Dev world in true DevOps testing bliss.
How to implement ruby on rails testing practices to build a successful web ap...Katy Slemon
In this blog, we write on both the test-driven development and the behavior-driven development who are RoR testing practices to build a successful web application.
Rspec and Capybara Intro Tutorial at RailsConf 2013Brian Sam-Bodden
Behavior-Driven Development and Acceptance Testing are heavily intertwined and in many aspects are one and the same. Both focus on starting at the outer layers of your application by concentrating on what matter to users; behavior. In this session/workshop we'll talk about how testing can be used both for specifying your application yet to be develop expected behavior and as accurate, running documentation that can be used to validate your stakeholder's acceptance criteria. We'll talk about the different types of testing and do a few hands-on exercises to flesh out a Rails application with RSpec and Capybara.
Test driven development is a popular concept in software development, leading to higher quality code that’s easier to maintain. Automated testing is normally a foreign concept in the operations world, but as you ssh into your servers to make that quick fix or run your updated script (fingers crossed), you might be wondering if there’s a better way. A way that gives you the confidence in your script and lets you test those scripts in isolation. Well Arthur has good news for you, there is a better way! Test driven infrastructure (TDI) is now possible. He knows, it sounds crazy.
At this session you’ll learn the how, and more importantly the why, of TDI. You’ll see how Chef (or any other Config Management framework) can be tested with Test Kitchen and ServerSpec. You’ll also learn how to improve your feedback cycle with Docker, and using the Docker approach on a CI server. There may even be some live demos!
Finally, the Ops world collides with the Dev world in true DevOps testing bliss.
Cross-platform Desktop Apps development using HTML, CSS, JS with ElectronEsinniobiwa Quareeb
Develop cross platform desktop apps with technologies you love (HTML, CSS and JS), wrap it up, make executable out of it using Electron and make installer using InstallForge
Deploying your rails application to a clean ubuntu 10Maurício Linhares
Learn how you can configure a new Ubuntu 10.04 machine to run your rails application with Nginx and Unicorn in a simple way including security setup and monit monitoring.
Cross-platform Desktop Apps development using HTML, CSS, JS with ElectronEsinniobiwa Quareeb
Develop cross platform desktop apps with technologies you love (HTML, CSS and JS), wrap it up, make executable out of it using Electron and make installer using InstallForge
Deploying your rails application to a clean ubuntu 10Maurício Linhares
Learn how you can configure a new Ubuntu 10.04 machine to run your rails application with Nginx and Unicorn in a simple way including security setup and monit monitoring.
Synthetic Fiber Construction in lab .pptxPavel ( NSTU)
Synthetic fiber production is a fascinating and complex field that blends chemistry, engineering, and environmental science. By understanding these aspects, students can gain a comprehensive view of synthetic fiber production, its impact on society and the environment, and the potential for future innovations. Synthetic fibers play a crucial role in modern society, impacting various aspects of daily life, industry, and the environment. ynthetic fibers are integral to modern life, offering a range of benefits from cost-effectiveness and versatility to innovative applications and performance characteristics. While they pose environmental challenges, ongoing research and development aim to create more sustainable and eco-friendly alternatives. Understanding the importance of synthetic fibers helps in appreciating their role in the economy, industry, and daily life, while also emphasizing the need for sustainable practices and innovation.
Normal Labour/ Stages of Labour/ Mechanism of LabourWasim Ak
Normal labor is also termed spontaneous labor, defined as the natural physiological process through which the fetus, placenta, and membranes are expelled from the uterus through the birth canal at term (37 to 42 weeks
Safalta Digital marketing institute in Noida, provide complete applications that encompass a huge range of virtual advertising and marketing additives, which includes search engine optimization, virtual communication advertising, pay-per-click on marketing, content material advertising, internet analytics, and greater. These university courses are designed for students who possess a comprehensive understanding of virtual marketing strategies and attributes.Safalta Digital Marketing Institute in Noida is a first choice for young individuals or students who are looking to start their careers in the field of digital advertising. The institute gives specialized courses designed and certification.
for beginners, providing thorough training in areas such as SEO, digital communication marketing, and PPC training in Noida. After finishing the program, students receive the certifications recognised by top different universitie, setting a strong foundation for a successful career in digital marketing.
Biological screening of herbal drugs: Introduction and Need for
Phyto-Pharmacological Screening, New Strategies for evaluating
Natural Products, In vitro evaluation techniques for Antioxidants, Antimicrobial and Anticancer drugs. In vivo evaluation techniques
for Anti-inflammatory, Antiulcer, Anticancer, Wound healing, Antidiabetic, Hepatoprotective, Cardio protective, Diuretics and
Antifertility, Toxicity studies as per OECD guidelines
A review of the growth of the Israel Genealogy Research Association Database Collection for the last 12 months. Our collection is now passed the 3 million mark and still growing. See which archives have contributed the most. See the different types of records we have, and which years have had records added. You can also see what we have for the future.
How to Make a Field invisible in Odoo 17Celine George
It is possible to hide or invisible some fields in odoo. Commonly using “invisible” attribute in the field definition to invisible the fields. This slide will show how to make a field invisible in odoo 17.
Acetabularia Information For Class 9 .docxvaibhavrinwa19
Acetabularia acetabulum is a single-celled green alga that in its vegetative state is morphologically differentiated into a basal rhizoid and an axially elongated stalk, which bears whorls of branching hairs. The single diploid nucleus resides in the rhizoid.
Operation “Blue Star” is the only event in the history of Independent India where the state went into war with its own people. Even after about 40 years it is not clear if it was culmination of states anger over people of the region, a political game of power or start of dictatorial chapter in the democratic setup.
The people of Punjab felt alienated from main stream due to denial of their just demands during a long democratic struggle since independence. As it happen all over the word, it led to militant struggle with great loss of lives of military, police and civilian personnel. Killing of Indira Gandhi and massacre of innocent Sikhs in Delhi and other India cities was also associated with this movement.
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...Dr. Vinod Kumar Kanvaria
Exploiting Artificial Intelligence for Empowering Researchers and Faculty,
International FDP on Fundamentals of Research in Social Sciences
at Integral University, Lucknow, 06.06.2024
By Dr. Vinod Kumar Kanvaria
Executive Directors Chat Leveraging AI for Diversity, Equity, and InclusionTechSoup
Let’s explore the intersection of technology and equity in the final session of our DEI series. Discover how AI tools, like ChatGPT, can be used to support and enhance your nonprofit's DEI initiatives. Participants will gain insights into practical AI applications and get tips for leveraging technology to advance their DEI goals.
Executive Directors Chat Leveraging AI for Diversity, Equity, and Inclusion
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
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