Is it possible to stub an auto-injected dependency?

Hello,

I’m wondering if it is possible to stub a container which is auto-injected? I have the following error: Dry::Container::Error: Nothing registered with the key "my_repo" at /dry-auto_inject-0.4.3/lib/dry/auto_inject/strategies/kwargs.rb:13 when I try to do so.

I guess it’s because the injection is done on class loading, before the test setup which calls the stub method. Here is a simplified version of my code:

module Domain
  class Repositories
    extend Dry::Container::Mixin
  end

  ImportRepositories = Dry::AutoInject(Repositories)

  class Service
    include ImportRepositories['my_repo']

    def list
      my_repo.all.sort_by(&:name)
    end
  end
end

describe Service do
  before do
    Domain::Repositories.enable_stubs!
    Domain::Repositories.stub(:my_repo, InMemoryRepository.new)
  end

  after { Domain::Repositories.unstub(:my_repo) }

  it 'test things' do
    # ...
  end
end

What do you think about it?

Hi there,

The error is preatty self explanatory, you did not registre my_repo check out the docs there http://dry-rb.org/gems/dry-auto_inject/

Your classes should look something like this:

module Domain
  module Repositories
    class MyRepo
      require 'ostruct'

      def all
        OpenStruct.new(name: 'Ionica')
      end
    end

    class Container
      extend Dry::Container::Mixin

      register 'my_repo' do
        MyRepo.new
      end
    end
  end

  ImportRepositories = Dry::AutoInject(Repositories::Container)

  class Service
    include ImportRepositories['my_repo']

    def list
      my_repo.all.sort_by(&:name)
    end
  end
end

I don’t want to register a Repo in my tests because several tests must be able to stub the repositories held by the container with different test implementations. To my understanding, that’s why containers can be stubbed.

I got it working without auto_inject, but it seems that auto_inject change this behaviour, and I am not sure if it’s a bug or a feature.