dry-rb / dry-container

A simple, configurable object container implemented in Ruby
https://dry-rb.org/gems/dry-container
MIT License
335 stars 41 forks source link

Reseting registry when testing #62

Closed ehannes closed 5 years ago

ehannes commented 5 years ago

Hi! Thanks for a great gem!

I have a question regarding testing. Is it possible to somehow unregister objects from the registry? I have a problem with leaking test object added to the registry.

Before I had this code:

    require 'dry/container/stub'
    Fortnox::API::Registry.enable_stubs!
    Fortnox::API::Registry.stub(:test, Model::Test)

Now I get an error: cannot stub "test" - no such key in container. When I try adding the test object to the registry before stubbing, as you suggest in the documentation, the first test passes but the second fails with:

     Dry::Container::Error:
       There is already an item registered with the key "test"

Also, I found below code in your own test suite. Unfortunately, I cannot do the same in my test since my registry includes other objects that I do not want to throw away :)

        after do
          # HACK: Have to reset the configuration so that it doesn't
          # interfere with other specs
          klass.configure do |config|
            config.registry = Dry::Container::Registry.new
          end
        end
flash-gordon commented 5 years ago

Use block with stub, rspec example:

around do |ex|
  Fortnox::API::Registry.stub(:test, Model::Test, &ex)
end

In future, use our forum and chat for asking questions (see CONTRIBUTING.md), this way you'd get the answer a lot faster.