Passionate about technologies, innovations.
Software Engineer @ Qubit

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:

Rspec.configuraiton.color_enabled = true

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:

require 'rspec'

Add multiple formatters to formater

RSpec.configure do |c| c.add_formatter(:documentation) c.add_formatter(:json) # built-in textmate formatter c.add_formatter(:textmate) end

Retrieve a list of formatters

formatters = RSpec.configuration.formatters

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:

require 'rspec'

config = RSpec.configuration

find built-in formatter class

documentation_klass = config.built_in_formatter(:documentation)

create a documentation formatter with STDOUT steam

documentation_formatter =$stdout)

build a json formatter

json_klass = config.built_in_formatter(:json)

create a JSON formatter with STDOUT steam

json_formatter =$stdout)

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

require 'rspec'

describe "Behaviour" do it "should pass" do true.should eq true end

it "should fail" do true.should eq false end

it "should pending" end