2013-07-11 5 views
1

,, : 및 일부 공백과 같은 모든 특수 문자를 제거하는 메서드를 테스트해야합니다.텍스트 파일에서 문자를 제거하는 방법에 대한 단위 테스트를 작성하려면 어떻게합니까?

테스트중인 메서드는 파일의 각 줄을 별도의 배열 위치에 저장합니다.

메서드가 텍스트 파일의 모든 특수 문자를 제거했는지 어떻게 테스트 할 수 있습니까?

+1

테스트중인 메서드의 코드 예제를 제공하면 코드 예제를 다시 얻을 가능성이 더 높습니다. – eebbesen

답변

1

메서드 호출 후에 파일을 작성하고 regex를 사용하여 원하지 않는 특수 문자가 없는지 확인하십시오. 또는 달성하고자하는 결과가 포함 된 파일과 파일 내용을 비교하십시오.

0

fakefs gem은 이런 종류의 작업에 적합합니다. 귀하의 사양 설정에서

(일반적 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 

여기 테스트중인 코드입니다. 마지막으로, 사양

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 

: 그리고 우리가 fakefs으로이 테스트의 설명 블록 태그 때문에

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 

은, 실제 파일 시스템 활동이 일어났다하지를이 기능은 모든 문장 부호를 제거합니다. 파일 시스템은 가짜 였고 모두 메모리에있었습니다.