Write your own custom RSpec formatter

Earlier this year I spent some time writing a custom RSpec formatter. The purpose in my case was to be able to automatically update a remote service with the results of testing some code. You can find that project here, jaribio_formatter.

The code for a basic no-op formatter is below. If you want to output a message when a group is started or finished, or an example starts or ends, or simply record failures to summarize at the end, all the hooks are well defined by RSpec though not well documented.

class MyRSpecFormatter

    attr_reader :output, :results, :example_group

    def initialize(output)
      @output = output || StringIO.new
      @results = {}
    end

    def start(example_count)
    end

    def example_group_started(example_group)
    end

    def example_group_finished(example_group)
    end

    def example_started(example)
    end

    def example_passed(example)
    end

    def example_pending(example)
    end

    def example_failed(example)
    end

    def message(message)
    end

    def stop
    end

    def start_dump()
    end

    def dump_pending()
    end

    def dump_failures()
    end

    def dump_summary(duration, example_count, failure_count, pending_count)
    end

    # no-op
    def seed(seed)
    end

    def close()
    end

end

You can also add your own custom configuration to RSpec. To do that, you need to call add_setting. An example from jaribio_formatter below. One more line of code calls this method when the formatter is required. The relevant source code to the jaribio_formatter is here if needed for reference.

    def self.configure()
      RSpec.configure do |c|
        c.add_setting :jaribio_url
        c.add_setting :jaribio_api_key
        c.add_setting :jaribio_plans, :default => []
        c.add_setting :jaribio_auto_create, :default => false
        c.add_setting :jaribio_timeout, :default => 5
      end
    end
Advertisements
This entry was posted in Uncategorized and tagged , , . Bookmark the permalink.

2 Responses to Write your own custom RSpec formatter

  1. Josh says:

    This is interesting, but where do I put this code?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s