Configuring a GitLab CI pipeline for Rails, MongoDB, and Rspec

Gitlab has a free private git repository service and an integrated CI service that can be configured to suit our needs. To know more about setting up Gitlab CI, check out our [blog post](link here)

Including MongoDB in CI build system

Instead of installing and starting MongoDB manually, we can use the Gitlab mongo service. A Gitlab service is just another Docker image that runs during your job and is linked to the main image. The first step is to include the latest MongoDB image to the build system. Add this to your .gitlab-ci.yml
services:
- mongo:latest

Add the MONGODB_URI variable

Add a variables section within .gitlab-ci.yml to set the MONGODB_URI variable.
variables:
MONGODB_URI: mongodb://mongo:27017/test_db

Add config/mongoid.yml ile

Add a file config/mongoid.yml.gitlab with the following contents
test:
  clients:
    default:
      uri: <%= ENV['MONGODB_URI'] %>

Override config/mongoid.yml with config/mongoid.yml.gitlab

We need to override the local test configuration with the above settings specific to CI. Add the following to the before_script section of .gitlab-ci.yml
before_script:
  - cp config/database.yml.gitlab config/database.yml
That’s it fellas, you are all set

Summary

The complete .gitlab-ci.yml
image: starefossen/ruby-node:latest
services:
  - mongo:latest
variables:
  MONGODB_URI: mongodb://mongo:27017/test_db
before_script:
  - RAILS_ENV=test bundle install --jobs $(nproc) "${FLAGS[@]}"
  - cp config/mongoid.yml.gitlab config/mongoid.yml
  - RAILS_ENV=test bundle exec rake db:create db:migrate
test:
  script:
    - bundle exec rspec
the contents of config/mongoid.yml
development:
  clients:
    default:
      database: dev_db
      hosts:
        - localhost:27017
      options:
        read:
          mode: :primary
        max_pool_size: 10
production:
  clients:
    default:
      uri: <%= ENV['MONGODB_URI'] %>
      pool_size: <%= ENV['DB_POOL_SIZE'] %>
test:
  clients:
    default:
      database: test_db
      hosts:
        - localhost:27017
      options:
        read:
          mode: :primary
        max_pool_size: 1
and config/mongoid.yml.gitlab
test:
  clients:
    default:
      uri: <%= ENV['MONGODB_URI'] %>
May you have a green build! :-)]]>