I want to know whether this solution is community approved by mocking object in ruby. If not please describe why, and how can I improve design of code or maybe test.
Consider I have the following code.
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
When testing I actually do not want anything to be created under path
that I defined in variable, so I just want to mock this behaviour
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
maybe should I do some class_double
of File
Class. I'm not sure about the way I provided, so I need some info how to do it in common/best-practices way