Test your app with RSpec
Created by Clemens Helm, @clemenshelm and Floor Drees, @floordrees
Updated by Ana Schwendler, @anaschwendler
This guide assumes that you have already built a Rails Girls app by following the app development guide.
RSpec is a Ruby testing framework, that describes our application’s behavior in a syntax that doesn’t look much like Ruby. It outputs test results in your terminal, so you’ll test your reading skills as well (pun intended).
COACH: Talk about testing and Behavior-Driven Development.
1. Add RSpec gem
Open up your Gemfile
and add this line to the :development
and :test
groups, above the end tag:
and run
to install the gem.
Next create the spec/
directory inside your application:
The spec/
directory is where your tests will reside. Finally run the following command:
This adds the following files which are used for configuration:
.rspec
spec/spec_helper.rb
spec/rails_helper.rb
2. Create your first test!
Rubyists often use the words ‘test’ and ‘specification’ interchangeably, that’s why you’ll store your tests in the ‘specs’ folder. To do that, do the following steps:
We will be creating a test for ou idea
model, to do that in the elegant way in Rails:
- Create a
models
folder in yourspec
folder, by running in the terminal:
- Save your test as
idea_spec.rb
(<model_name>_spec.rb
).
Inside that new file, in our first test we will want to guarantee that an idea has a name. In order to do that let’s describe one of our specifications:
In your terminal run
which will output that your test is pending as it’s not yet implemented.
COACH: Talk about googling terminal output.
Let’s do something about that!
should give you a more satisfying output.
3. Refactoring
You could actually also create two ideas, to be sure that our project is creating ideas in the right way:
which test more things.
COACH: Talk a bit about refactoring.
4. Marking to-do’s with tests
Yeah! To-do lists. Awesome. A nifty RSpec feature is the functionality to mark certain tests as pending. In other words, your first thinking about what the implementation should accomplish then write in a test to verify if it is working.
Let’s create our next test, by adding the lines below to our idea_spec.rb
will mark a test as pending.
Can you finish this test? Can you think about other tests?
5. Behavior-Driven Development
COACH: Talk a bit about Behavior-Driven Development.
By now you can create more tests alone. Feel free to talk to your coach to do that, or ways to create more tests.
Happy testing!