vendredi 2 décembre 2016

How can I correctly test in minitest that, on a bad path for a method call, a notification service gets called?

I am quite a newbie on minitest and I need help!

My environment, to begin with, is:

  • rails (4.2)
  • minitest (5.9.1) as test framework
  • mocha (1.2.1) as mock framework

Let's say that I have this Job class:

class GapCreationJob < ActiveJob::Base
  queue_as :default

  rescue_from ActiveRecord::RecordNotFound, StandardError do |error|
    handle_error(error)
  end

  def perform(gbu_id)
    # some code that might raise an exception...
  end

  private

  def handle_error(error)
    msg = "my message"
    Rollbar.warn(msg)
    Rails.logger.error "#{msg}\n  Detail: #{error.message}"
  end
end

How should I write a test that checks that - in case of exception - the Rollbar.warn gets called?

My problem, as newbie, is to write the expectation on the Rollbar class.

I've tried this, but it does not work:

require "test_helper"

class GapCreationJobTest < ActiveJob::TestCase
  setup do
    # code that sets up @import
    @import = ...

    Rollbar = mock('rollbar')
  end

  test "a completely failing import job should notify us on rollbar" do
    GuestBusinessUnit.any_instance.expects(:set_activities_all).raises(ActiveRecord::RecordNotFound)
    GapCreationJob.any_instance.expects(:handle_error) # this works, but it is not sufficient

    Rollbar.expects(:warn) # this expectation is not satisfied, even if - on the testing class - the real Rollbar.expects method gets called
    GapCreationJob.perform_now(@import.id)
  end
end

Here is the output when I run this test:

> rake test:jobs
Running via Spring preloader in process 27705
Started with run options --seed 62075

GapCreationJobTest
  test_create_guest_activity_plans_after_guest_business_unit_creation PASS (1.42s)
~/Development/proj/test/jobs/gap_creation_job_test.rb:9: warning: already initialized constant GapCreationJobTest::Rollbar
~/Development/proj/test/jobs/gap_creation_job_test.rb:9: warning: previous definition of Rollbar was here
  test_a_completely_failing_import_job_should_notify_the_creator  FAIL (0.02s)
Minitest::Assertion:         not all expectations were satisfied
        unsatisfied expectations:
        - expected exactly once, not yet invoked: #<Mock:rollbar>.warn(any_parameters)
        satisfied expectations:
        - expected exactly once, invoked once: #<AnyInstance:GuestBusinessUnit(id: integer, guest_id: integer, business_unit_id: integer, status: integer, datein: date, dateout: date, created_at: datetime, updated_at: datetime, idospite: string, conv_struttura: string, created_who: integer, updated_who: integer)>.set_activities_all(any_parameters)
        - expected exactly once, invoked once: #<AnyInstance:GapCreationJob>.handle_error(any_parameters)
        test/jobs/gap_creation_job_test.rb:22:in `block in <class:GapCreationJobTest>'

Thank you very much!

Aucun commentaire:

Enregistrer un commentaire