2011-12-16 46 views
2

在我的Rails/Rspec測試中,我正在刪除文件資源。我希望能夠在我的測試完成之後撤消任何這些更改,這與數據庫更改在事務中被撤銷的方式完全相同。如何撤消在Rails/RSpec測試中進行的文件系統更改?

  1. 如果我爲測試添加文件,我想在測試後刪除文件 。
  2. 如果我修改了一個測試文件,我希望文件 在測試後恢復到之前的狀態。
  3. 如果我刪除一個文件的測試,我想有文件恢復

是否有RSpec的或功能也許是不同的寶石,監視文件系統的變化,可以恢復到以前的狀態?或者我必須手動撤消這些更改嗎?

我目前正在運行Rails3,RSpec2和水豚。

回答

2

我不知道有哪些工具可以完全按照您的要求進行操作,但有一種方法可以執行以下操作: 1.在您的spec_helper.rb中添加before(:all)掛鉤增加每次測試後要恢復的目錄結構 2.在您的目錄結構上執行rm -r的spec_helper.rb中添加之前(:每次)和之後(:all)掛鉤,然後取消tar文件

另一種可能更有效的方法是使用rsync代替tar。我相信只有覆蓋需要覆蓋的更改纔是更智能的。

我相信這會實現你的目標。壞消息是,如果測試中止,你將不得不手動解壓文件。

實際上,這聽起來像是github上一個項目的好主意,如果還不存在的話。

+0

+1閱讀我的心靈上的所有三個想法。這就是我經歷的確切思路。特別是github項目。我很驚訝它不在那裏。 – plainjimbo 2011-12-17 07:43:03

4

我把Brian John的建議放在了他的所有觀點上,但我認爲我會從我的解決方案中發佈一些代碼,以防其他人想要做類似的事情。我還增加了一個自定義的元數據標籤的檢查,所以我只能這樣做時,我旗有測試組:文件符號

spec_helper.rb

注意,下面我支持我的#{Rails.root}public/system/ENV/files目錄(其中ENV =「test」或「develop」),因爲我正在使用它來測試回形針功能,這就是我的文件存儲位置。

此外,我正在使用我的備份文件中的--delete rysnc命令恢復目錄結構,而不僅僅是對目錄結構執行rm -r,這將刪除在測試期間創建的所有文件。

RSpec.configure do |config| 
    # So we can tag tests with our own symbols, like we can do for ':js' 
    # to signal that we should backup and restore the filesystem before 
    config.treat_symbols_as_metadata_keys_with_true_values = true 

    config.before(:each) do 
    # If the example group has been tagged with the :file symbol then we'll backup 
    # the /public/system/ENV directory so we can roll it back after the test is over 
    if example.metadata[:file] 
     `rsync -a #{Rails.root}/public/system/#{Rails.env}/files/ #{Rails.root}/public/system/#{Rails.env}/files.back` 
    end 
    end 

    config.after(:each) do 
    # If the example group has been tagged with the file symbol then we'll revert 
    # the /public/system/ENV directory to the backup file we created before the test 
    if example.metadata[:file] 
     `rsync -a --delete #{Rails.root}/public/system/#{Rails.env}/files.back/ #{Rails.root}/public/system/#{Rails.env}/files/` 
    end 
    end 
end 

sample_spec。RB

請注意,我加了標籤的它「應該創建一個新的文件」:文件符號

require 'spec_helper' 

describe "Lesson Player", :js => true do 

    it "should create a new file", :file do 
    # Do something that creates a new file 
    ... 
    end 

end