RSpec Tips & Tricks

Creative Commons License cell105

Throughout the last couple of days, I did a bigger refactoring of our Ruby on Rails application. As I changed quite a few moving parts, I covered everything I did with RSpec. It’s really an incredible feeling to have all your bases covered with automated tests when you finally start the manual regression test. Along the way, I came across a few things I wanted to share with you.

Structuring Your RSpec

When you’re writing specs you want to bring order to them sooner or later. I really use nested describe-blocks a lot. Let’s look into a Controller spec to see what I do:

Every controller spec starts with a describe block like this:

describe QuestionController do


For spec’ing out individual actions in the controller, I usually create one describe block for every public method in that controller:

describe QuestionController do
	describe "index" do

Inside that describe block I put all the it-specs themselves. Usually, I start by writing only the expectation and later I fill it out:

describe QuestionController do
	describe "index" do
		it "should redirect to 404, if no questions are found"
		it "should prepare a list of ten questions"
		it "should redirect a not logged in user to the login page"

Running specs from the command line

I use RubyMine for my ruby development but despite it’s capability of running specs within the IDE I prefer to run them separately on the command line. For running only the part you’re currently working on the -l parameter comes in handy. You can pass it any line number of an it or describe block and it runs only what’s there. This is especially cool for describe blocks as it runs all specs inside that block – and only those.

If you structure your specs like me using nested describe blocks, this is really nice.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.