lundi 2 mai 2016

Is stubbing appropriate for this activerecord query?

This code exists in a model:

  def self.ensure_exists(user_id:, coupon_id:, app_context: nil)
    candidate = where(user_id: user_id, coupon_id: coupon_id).first_or_initialize
    candidate.updated_at = Time.now.utc
    if candidate.new_record?
      log_invite_event!(app_context)
    end
...

private

  def log_invite_event!(app_context)
    invite = coupon.try(:invite)
    if invite.present?
      Event.create!(
        event_type: "Invites started",
        date: Time.now.utc,
        eventable: invite,
        description: "Invitee entered email address",
        app_context: app_context
      )
    end
  end

I want to test that log_invite_event! gets called on the candidate object. IN short, the method looks for an existing candidate, and takes the first one or initializes it. That first_or_initialize method is here

How do I test this? I have this as a start:

candidate = CouponCandidate.new
allow(CouponCandidate).to receive(:where).with(hash_including(user_id: user.id, coupon_id: coupon.id).and return(candidate)
allow(candidate).to receive(:first_or_initialize).and return(candidate)

expect(candidate).to receive(:log_invite_event).with(app_context)

subject

How do I test that private method? As written, I feel like I need to make that method non-private and have candidate be the explicit receiver. Right?

Aucun commentaire:

Enregistrer un commentaire