How do I write a unit test for a method which removes characters from a text file?

StackOverflow https://stackoverflow.com/questions/17583539

  •  02-06-2022
  •  | 
  •  

Вопрос

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?

Это было полезно?

Решение

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.

Другие советы

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.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top