Ruby on rails 如何在RSpec中模拟助手的方法
考虑一下gem中使用的以下代码,gem是我们主要应用程序的依赖项: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
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'))