Last active
February 28, 2023 07:47
-
-
Save sephraim/842c65033b2ade8d51bed626c40d6c06 to your computer and use it in GitHub Desktop.
[Test a method that writes to a file] Use RSpec to call a method that writes to a file and then test the contents of the file, all while ensuring that each created file immediately gets deleted after testing (i.e. temp file)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
RSpec.describe SomeClass do | |
describe '.some_method_that_writes_to_a_file' do | |
around(:example) do |example| | |
Dir.mktmpdir do |dir| | |
Dir.chdir(dir) do | |
example.run # Write file to a tmp directory that then gets deleted after each example | |
end | |
end | |
end | |
it 'has content' do | |
subject.some_method_that_writes_to_a_file | |
text = File.read('some_file.txt') | |
expect(text).to eql('Hello world!') | |
end | |
end | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
RSpec.describe SomeClass do | |
let(:tmpdir) { Dir.mktmpdir } | |
let(:csv_path) { File.join(tmpdir, SomeClass::DEFAULT_CSV_FILENAME) } | |
let(:perform_now) { described_class.perform_now } | |
let(:perform_later) { described_class.perform_later } | |
before(:example) do | |
# Generate files in a tmp directory (instead of, say, a downloads/ directory) | |
stub_const('SomeClass', SomeClass) | |
stub_const('SomeClass::DEFAULT_CSV_FILEPATH', csv_path) | |
end | |
after(:example) do | |
# Cleanup tmp directory | |
FileUtils.rm_rf(tmpdir) | |
end | |
it 'creates a new file' do | |
# Test method that specifically writes to the csv_path | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment