Example Changes of dependencies

I have looked at the berg example and did not see any changes of dependencies.
I want to stub some repositories for tests.
Can you provide relevant example for this case?

1 Like

You can simply pass in mocks into constructors, nothing special is needed, so ie:

require 'my_app/import'

class DoSomething
  include MyApp::Import[:repo]

  def call
    data = repo.some_method
    # do something
  end
end

RSpec.describe DoSomething do
  subject(:do_something) { DoSomething.new(repo) }

  let(:repo) { double(:fake_repo) }

  it 'works' do
    expect(repo).to receive(:listing).and_return(...)
    do_something.call
    # expect something
  end
end

For high-level integration tests you can use container’s stub API ie:

require "dry/container/stub"

MyApp::Container.enable_stubs!

MyApp::Container.stub(:repo, some_repo_stub)

# do something

MyApp::Container.unstub(:repo)

You can set up your tests/specs to stub things automatically for particular tests. At the moment dry-container doesn’t provide any test-lib-specific integrations, but I think we could very easily add that as it’s gonna be common so some conveniences here would be nice.

@solnic covered pretty much everything, but one thing I wanted to mention is that with the newer versions of dry-auto_inject and dry-component, the “kwargs” injection strategy is now the default, so for a class like this:

class DoSomething
  include MyApp::Import[:repo]

  def call
    data = repo.some_method
    # do something
  end
end

You’d pass your manual dependency with a keyword:

DoSomething.new(repo: my_repo)
2 Likes

Stubbing container keys was the one thing I was missing when I looked at Rodakase a while back. Great stuff!

Thank for answers!
I think it deserves to be reflected in documentation.
Especially, a fact that ‘AutoInject’ does injection through constructor.