Getting started with RSpec in Rails 3.2

Installing RSpec with Rails is pretty straight forward. The only task left since Bundler is to add RSpec to the Gemfile. And there is more good news, there is a special RSpec gem for Rails which has some handy shortcuts ready for you, I’ll be showing you some of those in future blog entries.

Quickest way is to append the gem to the Gemfile using the Console or Terminal just execute the following command in your project root directory(1):


echo "gem "rspec-rails", :group => [:test, :development]" >> Gemfile

Once you appended the RSpec gem install the gem via bundler i.e. bundle install.

We now got a new Rails generator commands:


Rspec:
  rspec:install

So lets install RSpec for our Rails project by running the following command rails g rspec:install

This will setup the RSpec environment in your Rails directory. Now we are ready to start cranking out RSpec tested code.

You may have noticed that we did not only add the gem to the test group but additionally to the development. You may ask yourself why? Well by adding it to the development group we get some more RSpec goodness. If you now use e.g.:


rails g model Something some_name some_description
      invoke  active_record

      create    db/migrate/20120207071500_create_somethings.rb
      create    app/models/something.rb
      invoke    rspec
      create      spec/models/something_spec.rb

Your Rails generator will automatically generate you the RSpec spec file. Let the BDD begin..

Sources:

RSpec book
Railscasts
Tekpub Rails 3 intro


(1)Or just simply open the Gemfile in the editor of choice and add the line: gem "rspec-rails", :group => [:test, :development]

Advertisements

From MySql Schema to Rails migration file

After skimming some forums I found the answer must be quite obvious to Rails developers. Simply make sure that your database.yml file (found in the config/ folder), references to your database. Then execute the following command:

rake db:schema:dump

Now browse to your db folder in which you will find the complete schema of your database within the schema.rb file. Please note that the file will be overwritten so you may want to rename it or split it up into single migration files according to each table.

Please note that this is for development purposes, and not intended to run the generated migration onto a production database.