【问题标题】:Where to cleanup cloudinary file uploads after rspec/cucumber runrspec/cucumber 运行后在哪里清理云文件上传
【发布时间】:2013-10-13 02:02:37
【问题描述】:

我在FactoryGirl 方法中使用fixture_file_upload 来测试文件上传。问题是清理数据库后,所有这些上传的文件都保留在Cloudinary上。

我一直在使用 Cloudinary::Api.delete_resources 使用 rake 任务来摆脱它们,但我宁愿在 DatabaseCleaner 删除所有相关的公共 ID 之前立即清理它们。

我应该在哪里干扰DatabaseCleaner 以从Cloudinary 中删除这些文件?

【问题讨论】:

    标签: ruby-on-rails rspec cucumber cloudinary


    【解决方案1】:

    基于@phoet 的输入,并考虑到 cloudinary 限制了您在一天内可以执行的 API 调用数量以及您可以在一次调用中清理的图像数量,我创建了一个类

    class CleanupCloudinary
      @@public_ids = []
    
      def self.add_public_ids
        Attachinary::File.all.each do |image|
          @@public_ids << image.public_id
    
          clean if @@public_ids.count == 100
        end
      end
    
      def self.clean
        Cloudinary::Api.delete_resources(@@public_ids) if @@public_ids.count > 0
    
        @@public_ids = []
      end
    end
    

    我使用如下:在我的工厂女孩​​文件中,我在创建广告后立即调用添加任何 public_ids:

    after(:build, :create) do 
      CleanupCloudinary.add_public_ids
    end
    

    在 env.rb 中,我添加了

    at_exit do
      CleanupCloudinary.clean
    end
    

    以及在 spec_helper.rb 中

    config.after(:suite) do
      CleanupCloudinary.clean
    end
    

    这导致在测试期间,每 100 个云图像后进行清理,并在测试后清理剩余部分

    【讨论】:

    • :buildoption 在after(:build, :create) do 中是无用的,因为它——显然——不会写入数据库。否则,要使其在 Minitest 中工作,请通过在 test_helper.rb 中添加 teardown { CleanupCloudinary.clean } 来替换 at_exitconfig.after
    【解决方案2】:

    我在这里有两种做事方式。

    首先,除非是集成测试,否则我不会将任何内容上传到 cloudinary。我会使用模拟、存根或测试替身。

    其次,如果你真的真的需要上传文件,无论出于何种原因,我都会写一个钩子,在你的测试的after_all钩子中自动清理。

    【讨论】:

    • 我正在使用 attachinary gem,与 cloudinary 结合使用,但还没有找到在我的模型中存根“has_attachment”指令的方法。是否存在在所有测试运行后运行的“after_all”?
    • 对每个测试文件都这样做,应该没有任何区别。
    • 这取决于:config.after(:each) { your_hook } 是 100% 干燥的。您还可以使用标签来标记必须运行的规范。 rspec 有无数种方法可以做到这一点。
    【解决方案3】:

    要使 @Danny 解决方案在 Minitest 中工作,而不是 at_exitconfig.after,请添加 test_helper.rb

    class ActiveSupport::TestCase
      ...
      Minitest.after_run do
        puts 'Cloudinary cleanup'
        CleanupCloudinary.clean
      end
    end
    

    如果您需要更频繁地清理,您可以在test_helper.rb 或特定测试文件中全局使用teardown { CleanupCloudinary.clean }

    当然在工厂里你还需要:

    after(:create) do 
      CleanupCloudinary.add_public_ids
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-06-24
      • 1970-01-01
      • 2011-09-02
      • 1970-01-01
      • 1970-01-01
      • 2014-10-19
      • 2013-09-29
      • 1970-01-01
      相关资源
      最近更新 更多