vendredi 30 octobre 2020

How do you stub and test a helper that invokes a different method depending on the object class passed to it?

I've got this helper which I'm trying to write tests for in Minitest. The helper calls another method depending on the object class I'm passing as an argument, like so:

  def label_for(object)
      status = object&.status
      case object.class.name
      when "Subscription"
        class_for_subscription_status(status)
      when "Payment"
        class_for_payment_status(status)
      when "Purchase"
        class_for_purchase_status(status)
      when "Invoice"
        class_for_invoice_status(status)
      when "Ticket"
        class_for_ticket_status(status)
  end

Each individual method is already tested somewhere else, so I just need to test that if I pass a class Subscription object to label_for, it will invoke class_for_subscription_status(status) and not something else.

This is the test I've come up with, but I get NoMethodError: undefined method ``class_for_subscription_status' for #<AuxiliariesHelperTest errors.

  test "#label_for(object) should invoke the right helper if object is of class Subscription" do
    AuxiliariesHelperTest.any_instance.stubs(:label_for).with(subscriptions(:user)).returns(:class_for_subscription_status)

    assert_equal class_for_subscription_status(subscriptions(:user).status), label_for(subscriptions(:user))
  end

What am I doing wrong?

Aucun commentaire:

Enregistrer un commentaire