foxlance
foxlance

Reputation: 73

How to mock a method from a helper in RSpec

Consider the following code used in a gem, a dependency of our main app:

module Module1
  module Module2
    module EnvInit
      def stub_env(name, value)
        stub_const('ENV', ENV.to_hash.merge(name => value))
      end
    end
  end
end

RSpec.configure do |config|
  config.include Module1::Module2::EnvInit
  config.before(:each) do
    stub_env('NAME', 'John Doe')
  end
end

Our main app uses .env files for our environment variables. However, the code above overrides ENV['NAME'] for some reason. We do not have access to this gem, so in order for our test to persist I wanted to mock when stub_env is called, like so:

before do
  # tried this with `allow_any_instance_of` as well
  allow(Module1::Module2::EnvInit).to receive(:stub_env).with('NAME','John Wayne')
end

OR

it "should match name to John Wayne" do
  EnvInit.any_instance.should_receive(:stub_env).with('NAME','John Wayne')
end

etc. I've tried various ways of mocking but none of my attempts to target stub_env works. All stub_env sees is John Doe.

Simply put, I want stub_env to receive value == John Wayne by way of mocks.

Upvotes: 2

Views: 1034

Answers (1)

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121000

Mocking is a process of changing the default behaviour to what you have desired. That said, you want to mock stub_env, receiving John Doe (as it is receiving "John Doe" in real life) and do putting "John Wayne" in the ENV instead.

allow_any_instance_of(Module1::Module2::EnvInit).to \
  receive(:stub_env).
    with('NAME', 'John Doe').
    and_return stub_const('ENV', ENV.to_hash.merge('NAME => 'John Wayne'))

Upvotes: 1

Related Questions