Rspec: How to Test File Operations and File Content

RSpec: how to test file operations and file content

I would suggest using StringIO for this and making sure your SUT accepts a stream to write to instead of a filename. That way, different files or outputs can be used (more reusable), including the string IO (good for testing)

So in your test code (assuming your SUT instance is sutObject and the serializer is named writeStuffTo:

testIO = StringIO.new
sutObject.writeStuffTo testIO
testIO.string.should == "Hello, world!"

String IO behaves like an open file. So if the code already can work with a File object, it will work with StringIO.

How to test write to file with rspec?

I think it is not a good idea to test standard library methods. Just cover it with

allow(File).to receive(:open).with('config/brakeman.yml', 'wb') do |file|
expect(file).to receive(:write).with(response.body)
end

And that should be enough, I think

Do not test code that already tested :)

How To test in rspec if file is deleted?

From your spec, it appears that you are mocking and stubbing correctly, but you never call check_status, so the stubs and mocks don't get used. You could change your example to something like:

it 'deletes the file' do
expect(File).to receive(:delete).with("test/status.txt")
MyModel.check_status
end

It would be better still to test this with an actual file, instead of mocks and stubs, so that it also tests that the file is in the correct location, that you have the necessary permissions, etc.

How do I test reading a file?

Global variables make code hard to test. You could use each_with_index:

File.open(filepath) do |file|
file.each_with_index do |line, index|
next if index == 0 # zero based
# ...
end
end

But it looks like you're parsing a CSV file with a header line. Therefore I'd use Ruby's CSV library:

require 'csv'

CSV.foreach(filepath, col_sep: "\t", headers: true, converters: :numeric) do |row|
@transactions << Transaction.new(row['phrase'], row['value'])
end

How do you run a single test/spec file in RSpec?

Or you can skip rake and use the 'rspec' command:

bundle exec rspec path/to/spec/file.rb

In your case I think as long as your ./spec/db_spec.rb file includes the appropriate helpers, it should work fine.

If you're using an older version of rspec it is:

bundle exec spec path/to/spec/file.rb

rspec testing file and fileutils

Use fakefs. It's perfect for the purpose.

RSpec: How to test file parser

Create a few specs which parse Tempfiles that you create containing valid and invalid input and ensure that the parse function returns the expected results (or exceptions).



Related Topics



Leave a reply



Submit