Enabling JUnit formatter for RSpec in Gitlab CI

It can be cumbersome sometimes to go and check Gitlab CI pipeline to see what automated tests failed. We can reduce number of extra clicks that developers have to perform through Gitlab GUI to see the results.

We can achive this by providing JUnit reports to be used and displayed nicely within each Merge Request.

To do this in RSpec in a Ruby application follow steps below:

Add rspec_junit_formatter to your gemfile and run bundle install.

group :test do
  gem "rspec_junit_formatter"
end

Now we have the formatter in our application, we can run:

RAILS_ENV=test bundle exec rspec --format RspecJunitFormatter --out rspec.xml

and see test results output as XML file in the project’s root folder.

To make sure Gitlab has access to this file on CI and can read it properly, add following lines to your .gitlab-ci.yml file. Asssuming you have a step for rspec, that would look like below:

rspec:
  stage: test
  script:
    - RAILS_ENV=test bundle exec rake db:create db:schema:load
    - RAILS_ENV=test bundle exec rspec --format RspecJunitFormatter --out rspec.xml
  artifacts:
    reports:
      junit: rspec.xml

Voila! Now push the commit to your Gitlab repo and see Gitlab automatically detecting RSpec tests and including the results within Merge Request.

Gitlab Merge Request with RSpec support