在夹具加载后运行代码



我正在使用带有Minitest和Searchkick gem的Rails 5.1,在我的系统测试中,我需要在ElasticSearch中索引数据以确保测试通过。

如果我添加断点并检查

class ActiveSupport::TestCase
  # Setup all fixtures in test/fixtures/*.yml for all tests in alphabetical order.
  fixtures :all
  require 'pry'; binding.pry
  # Add more helper methods to be used by all tests here...
end

的所有模型都有零条记录,假设我用以下方法重新创建了数据库: rails db:drop db:create db:migrate

那么如何在加载夹具后运行代码Model.reindex呢?

注意:我可以使用setup但这样我将在每次测试之前在所有需要的模型中重新索引,从而增加时间。

您可以在设置方法中使用类变量,如下所示:

class SomeTest
  setup do
    @@once ||= Model.reindex
  end
end

我在 CI 服务器上遇到了同样的问题。我通过在运行测试之前预加载测试数据库来修复它。

bin/rails db:fixtures:load

(来源:https://api.rubyonrails.org/v5.1.0/classes/ActiveRecord/FixtureSet.html(

相关内容

最新更新