I have a module like this that I'm trying to write unit tests for
module MyThing
module Helpers
def self.generate_archive
# ...
::Configuration.export(arg)
rescue ::Configuration::Error => error
raise error
end
end
end
The ::Configuration
module can't exist in my unit testing environment for reasons that are beyond my control, so I need to stub it out. Here's what I've come up with so far.
RSpec.describe 'MyThing' do
it 'generates an archive' do
configuration_stub = stub_const("::Configuration", Module.new)
configuration_error_stub = stub_const("::Configuration::Error", Class.new)
expect_any_instance_of(configuration_stub).to receive(:export).with("arg")
MyThing::Helpers.generate_archive
end
end
This gets me an error.
NoMethodError:
Undefined method `export' for Configuration:Module
If I put the configuration_stub
definition inline with the expect_any_instance_of
like this
RSpec.describe 'MyThing' do
it 'generates an archive' do
configuration_error_stub = stub_const("::Configuration::Error", Class.new)
expect_any_instance_of(stub_const("::Configuration", Module.new)).to receive(:export).with("arg")
MyThing::Helpers.generate_archive
end
end
I also get an error.
NameError:
Uninitialized constant Configuration::Error
...
# --- Caused by: ---
# NoMethodError:
# Undefined method `export' for Configuration:Module