Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 如何在RSpec中模拟助手的方法_Ruby On Rails_Ruby_Unit Testing_Rspec - Fatal编程技术网

Ruby on rails 如何在RSpec中模拟助手的方法

Ruby on rails 如何在RSpec中模拟助手的方法,ruby-on-rails,ruby,unit-testing,rspec,Ruby On Rails,Ruby,Unit Testing,Rspec,考虑一下gem中使用的以下代码,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.incl

考虑一下gem中使用的以下代码,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

等等。我尝试过各种各样的模仿方式,但我针对
stub\u env
的尝试都没有奏效。所有
stub\u env
看到的都是
johndoe


简单地说,我希望通过模拟的方式接收
stub\u env
值==John Wayne。

模拟是一个将默认行为更改为所需行为的过程。这就是说,你想要模仿
存根(stub_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'))

我刚才试过了,但没有成功。您似乎返回了相同的
stub_const
行,其中包含我希望保留的值(John Wayne),另一个更改是通过with()提供的值变为硬编码的值。仍然无法针对有问题的方法。无法模拟调用方。人们可以模仿被叫人。另外,我不明白为什么上述方法对您不起作用。对我来说,理想的解决方案是将binding.pry放在第5行,就在
stub\u const('ENV',ENV.to\u hash.merge(name=>value))
之前,检查
value
是否返回
John Wayne
。根据您的建议,
value==johndoe
。如果我退出
,我的测试将失败。谢谢你的调查。我期待着明天的第一件事就是回到这个对话中。
RSpec.configure
部分可能来自gem的一个spec文件。您不应该在应用程序中包含这些文件。如果包含gem会自动添加gem的测试设置,那么这是一个需要修复的严重错误。
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'))