RSpec Basics
Intro
Welcome to using RSpec! Here's a short intro to getting up to speed. If you're here after using m-spec, it was designed to help you quickly get to grips with RSpec. RSpec is an industry-standard tool for teams using Ruby, it's fully featured, well-documented, and helps you keep your test code DRY.
The trade-off for keeping code DRY is abstraction, and it can be tough for beginners to grapple with a lot of abstraction. So this repository is aimed for you to play with and learn by doing. Write specs, run the specs, read the comments in the files, explore and have fun! :)
Quick Setup
mkdir [dirname]
to create a new project directorycd
into the directorybundle init
to add a Gemfilebundle add rspec
to add rspecrspec --init
to initialise the framework
Inquiry Projects
1. What is the purpose of initial files that were created?
How can you run your tests with common options like colour and formatted output?
create .rspec
create spec/spec_helper.rb
2. Write a simple spec
In a new project directory, initialise RSpec and use it to write a simple spec. If you need inspiration, write your own spec for Animal#roar.
3. Use RSpec mocks in a spec
Practice using RSpec's double()
method. Write down your observations. Run irb
and play around with the methods. Or use pry
to pause your code path during a test run and explore.
4. Investigate
- How RSpec helps keep tests independent
- The difference between let and let!
- When to use before blocks
Resources
Usage Notes
- RSpec adds the
lib
directory to the load path if it's available, so you can use the require method relative from it - eg: simple usage spec - RSpec has it's own spec runner, so running
rspec
by itself runs all the specs it finds. - NB: RSpec will automatically try to find any spec in your
spec
directory named*_spec.rb
- pay attention to your file names. - To run an individual file, pass the filepath
rspec spec/tests_should_run_independently_spec.rb
- To run an individual test, pass the filepath and linenumber
rspec spec/tests_should_run_independently_spec.rb:17