collectiveidea / interactor

Interactor provides a common interface for performing complex user interactions.
MIT License
3.36k stars 212 forks source link

good way to use dependency injection when testing interactors? #181

Closed tansaku closed 3 years ago

tansaku commented 4 years ago

I have an interactor that reaches out to ruby Mail to send an email.

I was to test the situation where the mail fails to send and I'd usually use dependency injection to pass in a mail class double to simulate the failure ...

I was just wondering if there was a good pattern to use dependency injection for testing interactors, e.g.

    class MyEmaiInteractor
      include Interactor
      def call(mail_client = Mail)
        mail_client.deliver do
          from     'me@test.comt'
          to       'you@test.com'
          subject  'Test'
          body     'Some stuff'
        end
      end

so that in a test we can pass in a dummy mail client ...

sunny commented 4 years ago

You could do dependency injection by doing something like:

class MyEmailInteractor
  def call
    mail_client.deliver do
      …
    end
  end

  private

  def mail_client
    context.mail_client ||= Mail
  end
end
timlawrenz commented 3 years ago

@tansaku If this answer is satisfying, could you close the issue?