0

I'm creating spies for two classes belonging to the same namespace with the goal of expecting each to receive specific arguments:

allow(SibApiV3Sdk::SendSmtpEmail).to receive(:new).and_return(seb_send_email)
allow(SibApiV3Sdk::SMTPApi).to receive(:new).and_return(seb_smtp_api)

def seb_send_email
  @seb_smtp_api ||= SibApiV3Sdk::SendSmtpEmail.new(email_params)
end

def seb_smtp_api
  @seb_smtp_api ||= SibApiV3Sdk::SMTPApi.new
end

When I do, the second spy fails to work properly and returns the first spied object instead. I suspect this has something to do with it being a namespaced class. Is this the expected behavior and is there an alternative approach for handling namespaced class spies?

Luke Keller
  • 2,488
  • 3
  • 20
  • 23
  • the instance variable name in both methods is the same, so once you call the first method, you have already set the value, thus the `=` of the `||=` doesn't get called, and it just returns the already set value. Perhaps you meant `def seb_send_email; @seb_send_email ||= ... ` – Simple Lime Jul 15 '18 at 20:40

1 Answers1

2

You assign both to @seb_smtp_api variable and that's the source of your problems.

You probably call the seb_send_email method first, then it's memoized as @seb_smtp_api and when you call seb_smtp_api it just returns the memoized value.

You can check that by replacing allow with expect and see that SibApiV3Sdk::SMTPApi's new method is never called.

Greg
  • 5,862
  • 1
  • 25
  • 52