Create a Ruby RSpec test case for file input
I have a text file which I intend to convert to a CSV (in this case) format. How do I create a proper RSpec test to see if the output will be in the proper format for the following scenario?
This is my code:
class ProcessLog
@@log = Array.new
def read_log(log)
if File.exists?(log)
f = File.open(log, "r")
f.each_line { |line| @@log << line.strip }
end
end
def process_log
result = Array.new
@@log.each do开发者_开发知识库 |line|
<convert to csv>
result << <converted to csv>
end
result
end
end
describe ProcessLog do
before do
@pl = ProcessLog.new
<help>
end
it 'should pass first format' do
text = "Item X has a price of $ per gram" # just as an example
<help>
@pl.read_log("file.log")
@pl.should == 'X,$,gram'
end
end
First, you're using a class variable (@@log
) when you want an instance variable (@log
). But really there's no reason to use either.
I would split these methods up like so, so you can test them in isolation:
- One method that reads a file to an array, and returns the array
- One method that takes an array and formats them how you want them, returning the formatted array
Right now your methods are tightly coupled because they're both using the instance variable, and it makes testing harder than it needs to be (you have to set up or fake the call to the first method to begin testing the second).
You could test the first method with something like FakeFS to read the contents of a (fake) file. Really though this method should be fairly trivial and you might not have to test it at all.
The second method gets easier to test when you remove the coupling to the first. Create an array of lines from a file you expect to parse, and pass it to the method, and check the result.
精彩评论