2013-12-08 31 views
2

我想寫一些涉及文件操作的測試。我想使用一些假的文件系統(如外部服務的VCR),我發現fakeFS。不幸的是,無論我無法正確設置或破壞某些東西(我懷疑它是非常基本的功能),我準備了一個簡單的例子,說明我的意思,讓代碼說話:與Rspec和真正的文件系統FakeFS和Rspec incabiltency

有了真正的FS:

module MyModule 
    describe Something do 

    before(:all) do 
     File.open("#{Rails.root}/foo.txt", 'w+') { |f| f.write 'content'} 
    end 

    it 'should exist' do 
     expect(Pathname.new("#{Rails.root}/foo.txt").exist?).to be_true 
    end  

    it 'should still exist' do 
     expect(Pathname.new("#{Rails.root}/foo.txt").exist?).to be_true 
    end 
    end 
end 

運行提供了:

bash-4.2$ rspec 
.. 

Finished in 0.00161 seconds 
2 examples, 0 failures 

以這樣的方式添加fakeFS

require 'fakefs/spec_helpers' 

module MyModule 
    describe Something do 
    include FakeFS::SpecHelpers 

    FakeFS.activate! 
    FakeFS::FileSystem.clone(Rails.root) 

    before(:all) do 
     File.open("#{Rails.root}/foo.txt", 'w+') { |f| f.write 'content'} 
    end 

    it 'should exist' do 
     expect(Pathname.new("#{Rails.root}/foo.txt").exist?).to be_true 
    end  

    it 'should still exist' do 
     expect(Pathname.new("#{Rails.root}/foo.txt").exist?).to be_true 
    end 
    end 
end 

結果:

bash-4.2$ rspec 
.F 

Failures: 

    1) MyModule::Something should still exist 
    Failure/Error: expect(Pathname.new("#{Rails.root}/foo.txt").exist?).to be_true 
     expected: true value 
      got: false 
    # ./spec/models/something_spec.rb:23:in `block (2 levels) in <module:MyModule>' 

Finished in 0.00354 seconds 
2 examples, 1 failure 

所以它看起來像文件不通過隨後的測試依然存在。我誤解before(:all)是如何工作,或者我做錯了什麼?如果是這樣,那麼爲什麼該代碼與真實文件一起工

如果它不是一個bug,只是一個功能,那麼是否還有其他任何與真實文件系統一致的假文件系統寶石?或者我必須留在真實的文件中才能獲得測試......好,測試?

回答

2

我在創建這個問題後找到了答案,duh;)我查看了該lib的源代碼,發現suspicious line

而不是FakeFS::SpecHelpers我已經包含FakeFS::SpecHelpers::All這是相同的代碼,除了FakeFS::FileSystem沒有被清除後,每次調用,現在它的行爲是正確的。

+0

你是什麼意思包括FakeFS :: SpecHelpers :: All?你是否將它包含在每個使用fakefs的文件中?或者在spec_helper.rb中? – Matilda

+0

我的意思是'spec_helper.rb'。 – zrl3dx