mosquito-cr / mosquito

A background task runner for crystal applications supporting periodic (CRON) and manually queued jobs
MIT License
227 stars 24 forks source link

Provides a test backend (aka test mode) #117

Closed robacarp closed 1 year ago

robacarp commented 1 year ago

fixes #43

Two approaches were suggested in the issue:

The synchronous job pattern is used elsewhere and provides convenience for integration testing. A developer can then test "a user clicks this button and an email is sent to them". However it also adds code to the worker and runner -- something I try to avoid if at all possible to keep mosquito as fast as possible.

I've chosen to implement a testing backend which can be activated in the testing setup code for a project and all enqueues will simply get stored for later inspection / assertion. This avoids adding test_mode=true? checks to worker code. For situations where you need to test the affects of a job, use #run as usual.

It'll look like this:

  Mosquito.configure do |settings|
    settings.backend = Mosquito::TestBackend
  end

Then in your tests:

  describe "testing" do
    it "enqueues the job" do
      # build and enqueue a job
      job_run = EchoJob.new(text: "hello world").enqueue

      # assert that the job was enqueued
      lastest_enqueued_job = Mosquito::TestBackend.enqueued_jobs.last

      # check the job config
      assert_equal "hello world", latest_enqueued_job.config["text"]

      # check the job_id matches
      assert_equal job_run.id, latest_enqueued_job.id

      # optionally, truncate the history
      Mosquito::TestBackend.flush_enqueued_jobs!
    end
  end

This is a bare bones test helper, but I think it'll save me and other folks some headache.

jwoertink commented 1 year ago

Looks pretty straight forward. I dig it.