如何仅在Rails中播种一次测试数据库?

问题描述 投票:0回答:1

我有一个包含180,000个单词的大型词典,需要将其加载到数据库中才能运行我的应用程序,并且对于进行测试非常有用。不幸的是,这大约需要30分钟来播种数据库。无论如何,是否只能对数据库进行一次播种,甚至仅对数据库的一个表进行播种,并允许每次运行都刷新其他表?

ruby-on-rails database ruby-on-rails-5
1个回答
0
投票

您可以使用新的Rails 6 insert_all提高播种效率。这将使用单个insert_all创建多个记录,并且不会实例化模型。 OTOH它不会进行任何验证,因此请小心。

insert

或者,使用DictionaryWords.insert_all([ { word: "foo" }, { word: "bar" }, ])


但是最好不要全部写18万个字。

种子和固定装置的问题是它们“适合所有人”。它们必须涵盖所有可能的开发和测试情况。如果您需要重置数据库,种子将被吹走。

而是使用activerecord-import,并且仅加载测试所需的最小值。使用诸如factory的库来生成伪造但有效的数据。

例如...

Faker

然后在测试中根据需要创建单词。我在这里使用# Assuming you have classes called Dictionary and DictionaryWord factory :dictionary do end factory :dictionary_word do dictionary word { Faker::Lorem.unique.word } end

RSpec

并且如果您需要更多的单词来进行手动测试,请打开控制台并进行一些设置。

let(:dictionary) { create(:dictionary) }
let!(:words) { create_list(:dictionary_word, 3, dictionary: dictionary) }

context 'when the word is in the dictionary' do
  let(:word) { words.sample }

  it 'finds the word' do
    expect( dictionary.exists?(word) ).to be_truthy
  end
end

context 'when the word is not in the dictionary' do
  let(:word) { "septemburary" }

  it 'does not find the word' do
    expect( dictionary.exists?(word) ).to be_falsey
  end
end

这不是特别有效,但是您可能真的不需要180,000个单词。


© www.soinside.com 2019 - 2024. All rights reserved.