Using Rspec in your Rails Application

This week my goal was to become a better tester. Naturally, I took every opportunity to test my Rails applications with Rspec.

If you feel that you must get into TDDing but have been making excuses not had the time to do that yet, this is how you can get started. It is simpler that you think.

In your Rails project, go to Gemfile and make sure you have


group :development, :test do 
	gem 'rspec-rails'
end

back on your command line enter


bundle install

and after that

$ rails generate rspec:install

to create the specific configuration required to test your Rails application.
create .rspec
create spec/spec_helper.rb

The spec file should be in spec/lib/name_of_file

I made a tweet_spec.rb file as I was playing with a Twitter related application that I built.

spec/lib/tweet_spec.rb

In this file you typically write


require "rspec_helper"

require "file_name"

describe "Name of Class" do
  it "behavior of the object" do
    examples to be tested
  end
end

I wanted a tweet to be within 140 words so I wrote


require "rspec_helper"

require "tweet"

describe Tweet do
  it 'truncates the status to 140 characters' do
    tweet = Tweet.new(status: 'Nom nom nom' * 100)
    tweet.status.length.should be <= 140
  end
end

Then I ran my spec with the command

$rspec --color spec/lib/tweet.rb

This will give you a colors in your test results, red for failures and green for when they pass. You also have the command

$rspec --color --format documentation spec/lib/tweet.rb

This will give you output and nested examples to see what is clearly going on.

You can actually include these in the .rspec file so you don’t have to write these commands every time you run tests:

.rspec


--color
--format documentation

As soon as I ran rspec my tests failed as expected because I had not written any code for my object yet.

In lib/tweet.rb I wrote:

lib/tweet.rb


class Tweet
  attr_accessor :status
 
  def initialize(options={})
    self.status = options[:status]
  end

  def status=(status)
    @status = status ? status[0...140] : status
  end
end

I ran “$rspec –color –format documentation spec/lib/tweet.rb” again and the test passed.

This is how you can take the first step in applying TDD/BDD to your Ruby on Rails application.

Now it is your turn!

Advertisements

One thought on “Using Rspec in your Rails Application

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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