Write the file after your method call and use regex to ensure there are no special characters you don't want. Or compare file contents against a file that contains the result you wish to achieve.
How do I write a unit test for a method which removes characters from a text file?
Frage
I need to unit test a method which removes all the special characters like ,
, :
and some blank spaces.
The method under test stores each line of the file in a separate array position.
How do I test if the method removed all the special characters of a text file?
Lösung
Andere Tipps
The fakefs gem is good for this sort of thing.
In your spec setup (typically spec_helper.rb):
require 'fakefs/spec_helpers'
RSpec.configure do |config|
config.treat_symbols_as_metadata_keys_with_true_values = true
config.include FakeFS::SpecHelpers, fakefs: true
end
Here's the code under test. This function removes all punctuation:
require 'tempfile'
def remove_special_characters_from_file(path)
contents = File.open(path, 'r', &:read)
contents = contents.gsub(/\p{Punct}/, '')
File.open(path, 'w') do |file|
file.write contents
end
end
And, finally, the spec:
require 'fileutils'
describe 'remove_special_characters_from_file', :fakefs do
let(:path) {'/tmp/testfile'}
before(:each) do
FileUtils.mkdir_p(File.dirname(path))
File.open(path, 'w') do |file|
file.puts "Just a regular line."
end
remove_special_characters_from_file(path)
end
subject {File.open(path, 'r', &:read)}
it 'should preserve non-puncuation' do
expect(subject).to include 'Just a regular line'
end
it 'should not contain punctuation' do
expect(subject).to_not include '.'
end
end
Because we tagged this test's describe block with fakefs, no actual file system activity took place. The file system was fake, all in memory.
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow