Unit Testing: Thinking Patterns

Testing Custom Fields Insert

  • Do not go behind testing the core controllers. A better approach is to fabricate the desired object and assert whether the custom fields got added. The reason being, we generally add custom fields on server side DiscourseEvents.

    • Fabricate the object and call the desired server side event with the correct params using DiscourseEvent.trigger.
    • then assert whether the custom fields got added to the object or not.
  • Although, do add test for the controllers which you build into the plugin.

Testing custom fields update

  • Call the PostRevisor.revise! or any updated/edited event applicable explicitly and assert whether the fields got updated properly.

Testing Topic Lists

  • If you want to test whether the fields were serialized in the topic list, generate a topic list via TopicQuery. Again try to avoid firing a request to /latest.json etc.

Testing Models(Business Logic)

  • The methods created by ActiveRecord are already tested well :wink: . So Just test the ones created by you.


  • Create the relevant object(posts/topics/groups/categories) and pass it to YourSerializer.new and assert whether your new fields were added to the serializer or not. You may need to pass additional params to the serializer to refer to any official plugin or core discourse which might have a test for that serializer.

Cron Jobs

  • The key here is to test the logic. Have a look at core tests on how to test these.

Integration Tests

  • These are the tests of the kind, If something happens in the module x, does the module y reacts as expected.

Custom Controllers

  • Test the custom controllers built into the plugin by sending requests with correct HTTP Request Type(get, post, put etc.) and assert the correctness of the response.

General Advise

  • Focus on a single class/method at a time.

More coming in this space(code examples and gotchas).

This extends to hand testing too. I try to put as much logic into library modules as much as possible to avoid debugging within a live web session. Win:Win.

Surprisingly yes. I think this analogy is very helpful to write tests as well.

@merefield @fzngagan Remember, your plugin needs to be at 80% coverage by the end of October :slight_smile: Speaking of which, I should really get back onto CW’s tests…

Tell that to my clients ;). Sure. I will get back onto it well before then.

Is that just specs for now?

Yup 80% spec cov.