Writing Tests for Plugins

Rspec goal: 80% Coverage

I’d like to keep tackling rspec tests until we can reach at least 80% coverage on each of our respective plugins. On the coverage % front, Discourse has a useful gem called “simplecov” which will calculate the percentage of your code that is covered by tests based on what lines are touched in the course of a test suite. I’ve found that you can restrict SimpleCov to a plugin by adding the following to your spec/pugin_helper.rb file:

SimpleCov.configure do
  add_filter do |src|
    src.filename !~ /discourse-custom-wizard/ ||
    src.filename =~ /spec/
  end
end

Once this is added you run your plugin test suite like this to get a coverage report for your plugin:

bundle exec rake plugin:spec[plugin_name] COVERAGE=1

You’ll then see an additional line of output at the end of the tests:

Coverage report generated for RSpec to /Users/angusmcleod/discourse/discourse/coverage. 589 / 1213 LOC (48.56%) covered.

If you look at the coverage report, it’ll tell you exactly what lines of code are not being tested.

I got a head start on this today by writing up rspec and qunit tests for the multilingual plugin I’m building for Wikimedia.

Some tips

  1. You should require the spec/rails_helper at the top of each spec file

    require 'rails_helper'
    

    This will load all the necessary stuff for rspec testing, including whatever you put in plugin/spec/plugin_helper.rb.

    This means plugin_helper.rb is a good spot to put rspec global config. For example I wrapped all tests in a code block to ensure that non-local language data was properly loaded for each test, see: https://github.com/paviliondev/discourse-multilingual/blob/master/spec/plugin_helper.rb

  2. It’s easier to run qunit tests in the browser directly, than via the command line, e.g.

    http://localhost:3000/qunit?qunit_skip_core=1&qunit_single_plugin=discourse-multilingual
    
  3. For those who already have a .travis.yml file, e.g. events and tlp, this probably needs to be updated in line with the instructions here: Setting up plugin continuous integration tests on Travis CI - developers - Discourse Meta.

  4. You may find that data persists between tests, particularly data in the PluginStore. To ensure this doesn’t happen you can add this to your plugin_helper.rb file

RSpec.configure do |config|
  config.around(:each) do |example|
    ActiveRecord::Base.transaction do
      example.run
      raise ActiveRecord::Rollback
    end
  end
end
2 Likes