开发者

How to test directory?

开发者 https://www.devze.com 2023-04-06 07:13 出处:网络
I have a method helper which reads files and directory and build html view. Like this: def build_segment(path)

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


The difficulty you're having is because of how tightly coupled your code is. The same code is traversing directory structures and generating html.

Ideally, your code should be separated so that you have:

  1. a directory parser that builds a data structure from a given directory structure; then
  2. a renderer to build your html


This is more elegant way. A fake filesystem - fakefs


My suggestion is to stub and mock out the behavior of the internal things: Something like

Dir.stub(:new).with(path).and_return([list of File mocks?])

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号