我正在使用 RSpec 在 Rails 上测试我的类。
我想知道什么是测试调用私有(private)方法的好方法。
例如我有这个类:
Class Config
def configuration(overrides)
@config.merge(overrides)
end
private
def read_config_from_yml
@config ||= YAML.load()...
end
end
为了测试配置方法,我们需要以某种方式模拟 read_config_from_yml 方法。我知道简单地模拟私有(private)方法 read_config_from_yml
或实例变量 @config
是不好的,因为那样会弄乱对象的内部结构。
我能想到的是:
公开 read_config_from_yml
为配置添加 setter 方法(以避免模拟实例变量)
这些是黑客攻击吗?还有其他想法吗?
最佳答案
一个想法是在测试中实际创建 YAML 文件的副本。您可以截取您在生产代码中使用的文件的片段,将其写入预期的文件位置,并在测试完成后将其删除。
before do
File.open(file_path_here, 'w+') do |f|
f << <<-eof
config:
setting1: 'string'
setting2: 0
eof
end
end
after do
File.delete(file_path_here)
end
it 'does the thing' do
...
end
这将避免任何 stub 并允许您将您的方法保密。
关于ruby-on-rails - RSpec - 调用应该被模拟的私有(private)方法的测试方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39802090/