‘FactoryBot’ and ‘Faker’ for Testing - Veltris

‘FactoryBot’ and ‘Faker’ for Testing

November 8, 2020 | Apeksha singh

    Testing is the most vital part of development, without it our application will become rigid and might as well break as we add more features to it. Data is one of the requirements for a successful and complete testing, but the question is where do we get this data from? You might think of creating some imaginary data, well that is not a very good idea as we end up violating the DRY(do not repeat yourself) principle. Also if we have hundreds of test cases we cannot sit and create hundreds of imaginary data. So, the question is what do we do?

    The solution to is problem is using “Data Factory”. It is a blue print that allows us to create an object or collection of objects, with predefined values. There are several tools to create a factory, one such tool is ‘FactoryBot’. Factory Bot is a useful tool that allows us to call on a pre-made object with a short snippet within our tests. Combined with Faker, which allows us to randomise the object attributes based on a large internal library, we will be able to set up each test with minimal effort, and get back to coding our app as fast as possible. Setup is a breeze, and preparation is minimal compared to the time you spend creating objects by hand in each test file.

    The first step is to add ‘factory_bot_rails’ and ‘faker’ to our test group in the Gem file.

    group :development, :test do
      gem 'factory_bot_rails'
      gem 'faker'
    end

    After this, make sure to bundle install so that the changes made here will take effect. Next, add the following lines in test_helper.rb file:

    ENV['RAILS_ENV'] ||= 'test'
    require_relative '../config/environment'
    require 'rails/test_help'
    class ActiveSupport::TestCase
      # Run tests in parallel with specified workers
      parallelize(workers: :number_of_processors)
      include FactoryBot::Syntax::Methods
     
    end

    With everything in place now and all the settings done we can move forward with creating data. Lets take an example where we have a model named articles in our project and we have to write tests for it.

    create_table "articles", force: :cascade do |t|
        t.string "title", null: false
        t.text "text"
        t.datetime "created_at", precision: 6, null: false
        t.datetime "updated_at", precision: 6, null: false
      end

    Next step is to create test/factories directory, our factory will be inside this directory.

    Create a file named article.rb , factory for articles model will look like this:

    FactoryBot.define do
      factory :article do
        title { Faker::Name.title }
        text { Faker::Lorem.word }
      end 
    end 

    Now we move on to writing some tests for articles model inside the test/models/article_test.rb directory.

    require 'test_helper'
    class ArticleTest < ActiveSupport::TestCase
      test 'should save article' do
        article = create(:article)
        assert true, article.save
      end
      
      test 'title should be present' do
        article = create(:article, title: nil)
        article.valid?
        assert_not_empty article.errors[:title]
      end
    end

    Similarly we can create data for all the models in our project and successfully run tests for each model. This way we can save our time and complete testing efficiently.

    I hope this blog gave you a clear idea of what FactoryBot and Faker gems are and how we can use them. You can share your views by commenting and don’t forget to give👏(claps).

    Thank You.

    Related Articles