Monday 26 May 2014

Ruby: Create a Gem with TDD

So you want to create a ruby gem? No problem, let's get started by creating a basic Lorem Ipsum generator.

bundle gem lorem

Open up the 'lorem.gemspec' file and fill in the TODO's

Include in the gemspec your development dependencies like this:

s.add_development_dependency 'rspec'

Yes that's right, we want tests

Install dependencies by running:

bundle install

Add the spec directory in the gem root

mkdir spec

Create your rspec config file called '.rspec' in the project root with this content

--color
--format documentation

Create the spec_helper.rb file in this directory with the following content

require 'lorem'

Now write your first test in 'spec/lorem_spec.rb'

require 'spec_helper'
describe Lorem do
  describe '.ipsum' do
    it "should return 'Lorem ipsum dolor sit amet...'" do
      Lorem.ipsum.should include('Lorem ipsum dolor sit amet')
    end
  end
end

Now run your tests with:

rspec

And you should see it fail

Now implement the feature. Edit the lorem.rb file and in the Module place the following code:

def self.ipsum
  "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent venenatis pellentesque sodales. Aliquam ullamcorper diam in metus consequat, ac elementum quam tincidunt. Suspendisse odio nibh, iaculis non turpis eget, bibendum facilisis lacus. Donec ultrices feugiat eros sed cursus. Pellentesque laoreet lacus ac tristique laoreet. Integer feugiat massa quis mi tempus porttitor. Morbi eget mauris arcu. In hac habitasse platea dictumst. Proin id risus sagittis, bibendum sem at, commodo est. Vivamus vestibulum nisi auctor justo fringilla consectetur. Etiam ultricies sapien nibh, ac fermentum dolor ornare malesuada. Quisque commodo purus eu convallis sollicitudin."
end

Now run your test again:

rspec

And the test should pass

Set the version number in your 'version.rb' file

Add to git with

git add .

And commit

git commit -m 'Add .ipsum method'

Now install the gem with:

rake install

This will build the gem and install it locally

You are now ready to use your gem locally

In IRB you can do:

require 'lorem'
Lorem.ipsum

Or in rails app include in Gemfile:

gem 'lorem'

When you are ready to share your gem with the world you can upload it to rubygems.org (after creating rubygems account and github account)

rake release

Now make something more useful!