Ruby Testing with Rspec
Objectives
Name some of the concepts behind TDD
Describe how TDD fits into the Agile Methodology
Set up rspec for running tests in Ruby
Use a testing suite in the context of TDD
Test-Driven Development (TDD)
Test-driven development (TDD) is a software development process that relies on the repetition of a very short development cycle: first the developer writes an (initially failing) automated test case that defines a desired improvement or new function, then produces the minimum amount of code to pass that test, and finally refactors the new code to acceptable standards. - wiki
Process
Create / receive feature specification
Create test
Run tests (new test should fail)
Write code to try to make the test pass
Run tests (if fail return to step 4)
Refactor code if needed
How to get started
Rspec is the testing framework we are going to be using for Ruby (including Rails). To get started:
(you might have to sudo
this depending on your machine settings)
Once you have successfully installed rspec, create a new project:
Inside your .rspec file make sure you have this text
Requiring files
require
This will load a ruby file ONCE and only once. All subsequent require statements will not reload the file.
Doesn't need the .rb file extension, but won't hurt if it's there.
require_relative
Same as
require
, but will look for the file to require in the same directory
Rspec matchers
The rspec documentation is a great place to find more of these - you can find them here
Writing your first test
Create a new file in the spec
folder ending with _spec
. In this example, we'll name our first test tests_spec.rb
Start with requiring spec_helper
, then add a describe
block, and inside an it
statement as well
Let's start with some very simple tests
for more information see the RSpec documentation
I'm getting errors!
Make sure you have done
rspec --init
so that you have a .rspec file and a spec folder with a spec_helper.rb fileDid you mean to do
require_relative
instead ofrequire
?If you do use
require_relative
, make sure you have the exact path
Hooks
RSpec also supports before and after hooks which can be triggered before or after each example or once for the entire context (all things in a describe block). This is useful for doing things like initializing an instance of a class before testing it.
Here is a basic example using before
More details hooks in RSpec docs
Last updated