Testing with RSpec, FactoryGirl and Faker

Steven Philbert
map-tech-corner
Published in
2 min readFeb 22, 2017

Writing code without testing can let you (and your app) think that everything is working properly especially when you’re working on your own.
Thanks to tests, you can ensure your code adheres to the desired functionality even after some major code refactoring.

Since I just started getting into testing with RSpec myself, this article is aimed at helping Ruby on rails developers in setting up an RSpec test suite, in the Behaviour Driven Development.
Aware that there are lots of resources online to help you on this journey, this one is only a cheat sheet :)

First of all, let’s describe the tools used at monAlbumPhoto :

RSpec : a testing framework for Rails 3.x, 4.x and 5.0. — The framework to handle our testing activities
FactoryGirl : a fixtures replacement, which helps to build attributes for resources.
Faker : A library for generating fake data such as names, addresses, and phone numbers (and even some pokemons)

Setting up :

We first add all the needed gems to our Gemfile, usually in the test and development group:

then run

$ bundle install

To set up RSpec, we need to generate the spec files by running the command:

$ rails generate rspec:install

This will create the following files which are used for configurations:

.rspec
spec/spec_helper.rb
spec/rails_helper.rb

At this point, RSpec is well set up, and running $ bundle exec rspec will run our tests.

Creating a Factory

Assuming you have a contact model, let’s create a directory named factories in your spec folder

Models Specs

We want to ensure that the factory we created above is valid for the model. Create a file in your model/spec folder for your model:

From your terminal run:

$ rspec spec/models/contact_spec.rb

Your first test should pass :)

--

--