我想知道这个解决方案是否通过在 ruby 中模拟对象得到社区的认可。如果不是,请描述原因,以及如何改进代码设计或测试。
考虑我有以下代码。
lib/config_loader.rb
class ConfigLoader
HOME_DIR = '~/my/home_dir'.freeze
...
def load(path)
path = File.expand_path(path)
if File.exist?(path)
File.read(path)
else
File.read(HOME_DIR)
end
end
end
在测试时,我实际上不希望在path
我在变量中定义的内容下创建任何东西,所以我只想模拟这种行为
spec/lib/config_loader_spec.rb
RSpec.describe ConfigLoader do
describe '.load' do
subject { described.class.new.load(path) }
let(:path) { 'path/that/should/exist' }
context 'when path' do
before do
allow(File).to receive(:exist?).with(path).and_return(true)
allow(File).to receive(:read).with(path).and_return('my content')
end
it { expect { subject }.to_not raise_error { Errno::ENOENT }
end
end
end
也许我应该做一些class_double
课程File
。我不确定我提供的方式,所以我需要一些信息如何以常见/最佳实践的方式进行