Search code examples
ruby-on-railsunit-testingfactories

Cannot access seeds in my factories when running Rails unit tests


I have factories that include some setup data. For example:

Factory.define :event do |event|
  event.name  { Factory.next(:email) }
  event.blurb "Test event blurb"
  event.association(:owner, :factory => :user)
  event.countries Country.all
end

Country.all just assigns all countries from a lookup table to that particular event. I include all the countries by loading seeds before I run my tests with this line in my test helper:

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

This works great when running individual unit tests:

ruby test/unit/event_test.rb

However Country.all returns nothing when I run the test using:

rake test:units

Does anyone know why this is happening?


Solution

  • You require seeds in the test_helper, it's loaded once. After each test run database is wiped out, including seeded data. In order to make seeds load every time, add something like this to your test_helper's ActiveSupport::TestCase class definition.

    class ActiveSupport::TestCase
      # this line:
      setup { load "#{Rails.root}/db/seeds" }
    end