如何在RSpec中从帮助器模拟方法

时间:2017-06-27 06:45:21

标签: ruby-on-rails ruby unit-testing rspec

考虑gem中使用的以下代码,我们的主应用程序的依赖项:

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

我们的主应用程序使用.env文件作为环境变量。但是,由于某些原因,上面的代码会覆盖ENV['NAME']。我们无法访问这个gem,所以为了让我们的测试持续存在,我想在调用stub_env时进行模拟,如下所示:

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

等。我尝试了各种嘲弄方式,但我没有尝试定位stub_env。所有stub_env看到的都是John Doe

简单地说,我希望stub_env通过模拟方式接收value == John Wayne

1 个答案:

答案 0 :(得分:1)

模拟是将默认行为更改为您所需的过程。也就是说,你想模仿stub_env接收John Doe (因为它在现实生活中正在接收"John Doe")并将"John Wayne"放入而是ENV

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'))
相关问题