Search code examples
ruby-on-railsrubyrspecsendinblue

Spying on Classes of the Same Namespace


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?


Solution

  • 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.