With RSpec, how to seed the database on load?

后端 未结 6 1424
一个人的身影
一个人的身影 2021-01-30 03:28

I\'m using rspec for testing w my rails 3 app. I need to seed the database before the tests start. How can I seed the database with the following:

/db/seeds.rb

6条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-30 03:43

    I've followed the raging debate over at Auto-load the seed data from db/seeds.rb with rake. Die-hards maintain that you should never load seed data for tests, but I take the more moderate stance that there are occasions where you might want to load seed data for specific tests, e.g. verifying that the seed data exists.

    Unlike some answers given here, I do not recommend unconditionally loading the seeds from inside your spec_helper file. Instead, you can load your seeds using before :each or before :all inside just those test files that need the seeds, e.g.:

    describe "db seed tests" do
      before(:each) do
        load "#{Rails.root}/db/seeds.rb" 
      end
    
      ...your test code here...
    end
    

    update

    As @marzapower points out, if you go this route, your seeds.db file should clear each table before creating entries or use find_or_create_by methods. (Hint: the former is faster and more reliable.) This will prevent duplicate entries if you load the seeds.db file more than once.

提交回复
热议问题