Rails3 - Mocking the filesystem with RSpec
I've just finished the Rails3Tutorial book and I'm trying my first real world rails dev. (Feels like driving alone for the first time just after passing the test - scary).
Anyhoo, here's my problem. I'd like to list the contents of a directory on a web page. Simple enough, but I have a few questions. I'm using RSpec by the way
Firstly, how do I test drive the solution? I need to mock the filesystem so I can dictate the results of Dir.entries (or similar) for the test case. I know I cou开发者_运维知识库ld write the contents of the directory in the before(:each) block and then clean up after the test but that feels clumsy. I know how to create a stub for the Dir objects and how to force the results, but how do I get that stubbed object into the controller. I want to use the mocked object during testing and the real thing for production. How do I do that?
Secondly, where should I put the code that inspects the file system. I'm not really using a database for this since I'm building info by looking at the directory. So should there be a model at all? Or should I do the heavy lifting in the controller?
I'm sure I'm staring the solution in the face, but any help you can give will help me make my first tentative steps into Rails loveliness. So thanks in advance.
All your business logic should be in your models, or in modules in your library. Your controller should be dumb and should only pass information form the browser to your models, and then display information via views.
In your specific case, the Dir class is what handles files inside a directory. All code that cares about how your "stuff" is stored should be in models.
This will give you an array of file paths in this directory
Dir.new("your_file_path").entries
If you want to stub these, you'll do something like
directory = Dir.new("/") #obviously using *nix here
directory.stub!(:entries).and_return(["fakefile.txt"])
puts directory.entries
精彩评论