如何撤消在Rails/RSpec测试中进行的文件系统更改?

pla*_*mbo 3 testing ruby-on-rails rspec2

在我的Rails/Rspec测试中,我是CRUD的文件资源.我希望能够在我的测试完成之后撤消任何这些更改,就像使用事务撤消数据库更改一样.

  1. 如果我为测试添加一个文件,我想在测试后删除该文件.
  2. 如果我为测试修改文件,我希望在测试后将文件恢复到先前的状态.
  3. 如果我删除了一个测试文件,我想恢复该文件

RSpec中是否有一个功能,或者可能是一个监视文件系统更改并可以恢复到以前状态的不同Gem?或者我必须手动撤消这些更改吗?

我目前正在运行Rails3,RSpec2和Capybara.

pla*_*mbo 5

我接受了Brian John关于他所有观点的建议,但我认为我会从我的解决方案中发布一些代码,以防其他人想要做类似的事情.我还添加了对自定义元数据标记的检查,因此我只在使用:file符号标记测试组时才执行此操作

spec_helper.rb

请注意,下面我正在备份我的#{Rails.root}public/system/ENV/files目录(其中ENV ="test"或"develop"),因为我正在使用它来测试回形针功能,这就是我的文件存储的地方.

此外,rm -r我还没有在目录结构上执行操作,而是使用--delete备份文件中的rysnc命令进行恢复,这将删除在测试期间创建的所有文件.

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
Run Code Online (Sandbox Code Playgroud)

sample_spec.rb

请注意,我已使用:file符号标记它"应该创建一个新文件"

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
Run Code Online (Sandbox Code Playgroud)