development

db : seed 데이터를 테스트 데이터베이스에 자동으로로드하는 방법은 무엇입니까?

big-blog 2020. 7. 20. 07:10
반응형

db : seed 데이터를 테스트 데이터베이스에 자동으로로드하는 방법은 무엇입니까?


db:seed갈퀴 작업 인 Rails 2.3.4 이상에서 시드 데이터를로드하는 새로운 표준 방법을 사용하려고합니다 .

내 응용 프로그램이 제대로 작동하는 데 필요한 상수 데이터를로드하고 있습니다.

db:seed테스트 전에 작업을 실행 하는 가장 좋은 방법은 무엇입니까 ? 데이터가 미리 채워져 있습니까?


db:seed레이크 작업은 주로 단지로드 db/seeds.rb스크립트를. 따라서 해당 파일을 실행하여 데이터를로드하십시오.

load "#{Rails.root}/db/seeds.rb"

# or

Rails.application.load_seed

배치 위치는 사용중인 테스트 프레임 워크 및 모든 테스트 전에로드할지 또는 처음에 한 번로드할지에 따라 다릅니다. setup전화 나 test_helper.rb파일 넣을 수 있습니다.


나는 그것이 있어야한다고 말하고 싶었다.

namespace :db do
  namespace :test do
    task :prepare => :environment do
      Rake::Task["db:seed"].invoke
    end
  end
end

config.active_record.schema_format = : sql (db : test : clone_structure는) 인 경우 db : test : load가 실행되지 않기 때문에


lib / tasks / test_seed.rake에 이와 같은 것을 넣으면 db : test : load 이후에 seed 작업을 호출해야합니다.

namespace :db do
  namespace :test do
    task :load => :environment do
      Rake::Task["db:seed"].invoke
    end
  end
end

저는 믿습니다 스티브의 댓글이 위의 정답해야합니다. Rails.application.load_seed시드 데이터를 테스트 환경에로드 하는 사용할 수 있습니다 . 그러나이 데이터가로드되는시기와 빈도는 몇 가지 사항에 따라 다릅니다.

최소 사용

모든 테스트 전에이 파일을 한 번만 실행할 수있는 편리한 방법은 없습니다 ( 이 Github 문제 참조 ). 테스트 파일의 설정 방법에서 각 테스트 전에 데이터를 한 번로드해야합니다.

# test/models/my_model_test.rb
class LevelTest < ActiveSupport::TestCase

  def setup
    Rails.application.load_seed
  end

  # tests here...

end

RSpec 사용

before(:all)이 모델의 모든 테스트에 대한 시드 데이터를로드 하려면 RSpec의 방법을 사용하십시오 .

describe MyModel do
  before(:all) do
  Rails.application.load_seed
end

describe "my model..." do
  # your tests here
end

도움이 되었기를 바랍니다.


We're invoking db:seed as a part of db:test:prepare, with:

Rake::Task["db:seed"].invoke

That way, the seed data is loaded once for the entire test run, and not once per test class.


For those using seedbank, it changes how seeds are loaded, so you probably can't/don't want to use the load ... solution provided here.

And just putting Rake::Task['db:seed'].invoke into test_helper resulted in:

Don't know how to build task 'db:seed' (RuntimeError)

But when we added load_tasks before that, it worked:

MyApp::Application.load_tasks
Rake::Task['db:seed'].invoke

Adding Rake::Task["db:seed"].invoke to the db:test:prepare rake task did not work for me. If I prepared the database with rake db:test:prepare, and then entered the console within the test environment, all my seeds were there. However, the seeds did not persist between my tests.

Adding load "#{Rails.root}/db/seeds.rb" to my setup method worked fine, though.

I would love to get these seeds to load automatically and persist, but I haven't found a way to do that yet!

참고URL : https://stackoverflow.com/questions/1574797/how-to-load-dbseed-data-into-test-database-automatically

반응형