Passionate about technologies, innovations.

Programmatically Execute RSpec and Capture RSpec Test Results

RSpec is not merely a BDD test framework, it also packages a set of classes and methods you can use to bulid test utilities on top of RSpec stack. We will take a look at Rspec.configuration, RSpec::Core::Reporter, RSpec::Core::Formatters and RSpec::Core::Runner.


RSpec reads commandline configuration from global ~/.rspec file or project specific .rspec file in project folder. What really runs underneath is Rspec.configuraion that allows setup those commandline options programmatically. For example, before test execution, you can set commandline output pass or fail colour by:

400: Invalid request

RSpec::Core::Formatters, RSpec::Core::Reporter

RSpec ships a list of formatters, default is progress formatter. There are seveal ways to configure a formatter through configuration, or even custom formatters.The following snipt adds multiple formatters to configuration:

400: Invalid request

The drawback is that you have to loop through the formatters array to obtain a target formatter in order to make further test result manipulation. The following example gives more control over formatter objects, it also show how to contstruct a RSpect reporter instance:

400: Invalid request

Creates JSON Report with Reporter

Reporter can be passed to configuration by set the @reporter instance in RSpec.configuration. The following is full code example contains:

  • an example spec test, including one pass, fail and pending
  • rspec test runner
  • hashed result produced by JSON formatter and reporter

400: Invalid request