Create the simplest Ruby project to get started

Merce Bauza
3 min readNov 12, 2018

--

Setting up a project/environment is always the first challenge you face when you are learning a new language.

Although creating a Ruby project is not a difficult task, it might seem so when you are first starting or when you are doing it for first time. Having to understand all the necessary files to run a project might feel a bit overwhelming, specially when you are not familiar with the terminology and structure.

Luckily, we have tools that could help us with the setting up and other configurations.

BUNDLER & GEMFILE

Bundle is the most commonly used tool or gem (as Ruby packages are called) that could help with the management of the dependencies in the project (test libraries,…)

Bundler needs to be installed in our system first and once successfully installed, the command bundle should be accessible to use.

In a new terminal window, run the following command:

gem install bundler

One way to test if you have already installed it, it is running the following command and checking that a path is returned.

which bundler

To follow, create a project directory.

mkdir ~/Workspace/coin_changer && cd ~/Workspace/coin_changer

Set bundle as your dependency manager running the following command:

bundle init

Bundle will automatically create a Gemfile, a file where your project dependencies will be specified.

STRUCTURE

The most common structure used for a ruby project is to have two main directories:

  1. A directory called lib that will contain the source files.
mkdir lib && cd lib

For a simplest project, just create a .rb file to include your source code:

touch coin_changer.rb

2. A spec directory that will contain the tests.

mkdir spec && cd spec

Create the test file for the .rb file, previously created.

Important! spec files have to be named with a _specsuffix or the tests will not run.

touch coin_changer_spec.rb

Even the simplest project needs to have tests to test the source code.

|- lib
|- coin_changer.rb
|
|- spec
|- coin_changer_spec.rb
|
|- Gemfile

RSPEC

Rspec is a testing framework that will help creating a running tests in Ruby. In order to work, it needs to be added to the Gemfile of your project.

Include the RSpec dependency in the list of gems of the Gemfile:

source "https://rubygems.org"
gem 'rspec', '~> 3.0'

Install the dependencies (RSpec in this case) with bundle:

bundle install

and initiate it:

rspec --init

The previous command will also add a spec_helper.rb file to the spec directory.

|- lib
|- coin_changer.rb
|
|- spec
|- spec_helper.rb
|- coin_changer_spec.rb
|
|- Gemfile
|- Gemfile.lock

To run the tests, now you will only need to run the following command:

rspec

CONCLUSION

Setting up a project can sometimes be a bit frustrating (as it never works first time!) but it helps when you have a bit of guidance and it gets better with practice.

--

--