I have a method helper which reads files and directory and build html view. Like this:
def build_segment(path)
html = ""
Dir.new(path).each do |f|
next if f == "." or f == ".."
html << "<li>"
if File.ftype(f) == 'directory'
html << "<span class=folder>#{h(f.to_s)}</span>"
html << "<ul>"
html << build_segment(Dir.new(f))
html << "</ul>"
elsif File.ftype(f) == 'file'
html << "<span class=file>#{h(f.to_s)} </span>"
end
html << "</li>"
end
html
end
Usually to test some method we using mock objects – to send a fake object to testing method.
But here’s real file system. I can invent only one variant – create fake files on OS and then test the method.
Is there more neat and smart way to test this method? Thanks
My suggestion is to stub and mock out the behavior of the internal things: Something like
This way you can be sure you are only testing your code and not the code from the various ruby libraries you’re using.
I find myself doing this with things like http based behavior. If I’m using the ruby http libraries not only do I not want to waste time testing those things but it’s expensive to actually fire off http requests and wait for responses. Stubbing those things out allows me to test how my code reacts to certain response types.
I think it’s all about isolation.