Test your app with RSpec
Created by Clemens Helm, @clemenshelm and Floor Drees, @floordrees
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.
Install rspec
For starters, let’s install RSpec and all of its dependencies.
Then we call
in our project directory. This creates spec_helper.rb
in the spec folder, and .rspec
.
Rubyists often use the words ‘test’ and ‘specification’ interchangeably, that’s why you’ll store your tests in the ‘specs’ folder. Save your test as idea_spec.rb
(<name_of_spec>_spec.rb
).
Inside that new file, write:
Next, 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.
####Refactoring
You could actually also write:
which looks a lot nicer, but there’s a lot of magic involved. For now it’s probably just nice to know that we can ‘refactor’ those big chuncks of code into smaller bits with a little more experience.
COACH: Talk a bit about refactoring.
Marking to-do’s with tests
Yeah! To-do lists. Awesome. A nifty RSpec feature is the functionality to mark certain tests as pending.
Leaving out the do
and the end
in the example body, like so
will mark a test as pending. For bigger applications, where you want to tackle one test at a time, you can also add an x
in front of an example, making it read
or use the word pending
in your example.
Behavior-Driven Development
Normally we would go about BDD testing in a slightly different way. Thinking about the application we want to build, we’ll write down our expectations and then start building step by step, with the specifications in mind.
We’d first write
and only then create a file named idea.rb
introducing the idea class
as running rspec spec/lib/idea_spec.rb
in your terminal before you’ve implemented that class will throw you an error. Luckely, errors are nothing to be afraid of. RSpec errors actually help you write (the necessary) code!
Try and write tests for the follow up guides to check if you’re implementing ALL the right things.
Just saying.
Happy testing!