Rails unit testing doesn't load fixtures
-
20-09-2019 - |
Question
rake test:units
fails in my current application, because the needed data of the fixtures is missing.
If I'm loading the fixtures manually via rake db:fixtures:load RAILS_ENV=test
the unit tests are working, but rake purges the test database.
My test_helper includes fixtures :all
and my tests are inheriting from it - but the fixtures are simply not loading.
I'm kind of clueless at the moment and could really need some help!
I've tried a lot and I think it has to do with some environment settings or plugins used in this project. Does anyone know where to read about which files are loaded for the testing environment?
Solution 3
I finally found the problem, although the solutions is kind of hacky.
One plugin is relying that there is some data in the database, at least one row. So what happened was:
- rake loads database schema
- rake tries to load environment
- environment includes plugin
- plugin loading fails because of missing at least one row
- no fixtures are loaded
The hacky solution is: put the needed data directly into schema and not into a fixtures, because it's loaded to late.
I'll search for a more convenient solution and will update this answer if I found one.
OTHER TIPS
Another approach is to write your own custom rake task for testing.
For example:
task :test_units do
RAILS_ENV = 'test' # Force the environment to test
puts "Recreate the test database"
Rake::Task['db:test:prepare'].invoke
puts "Seed the database with fixtures"
Rake::Task['db:fixtures:load'].invoke
puts "Executing Unit Tests"
Rake::Task['test:units'].prerequisites.clear
Rake::Task['test:units'].invoke
end
Put the call to fixtures :all
in your test class, not the super class (test_helper). My guess is that initialization of the super class isn't working the way you're expecting and that fixtures :all
isn't be called. Perhaps try putting the call in the initialize method of test_helper.
My test/test_helper.rb
looks like this:
ENV['RAILS_ENV'] ||= 'test'
require File.expand_path('../../config/environment', __FILE__)
require 'rails/test_help'
class ActiveSupport::TestCase
# Setup all fixtures in test/fixtures/*.yml for all tests in alphabetical order.
fixtures :all
# Add more helper methods to be used by all tests here...
end
Not sure if you already did this, but export the test data from the database to the yml files in test/fixtures using a plugin like ar_fixtures
I had the same problem. Or rather, the problem was that my fixtures were not current with the database schema. Instead of throwing an exception, rails just used the test database as a fallback solution. Most iffy.
My problem is forgot to put "require 'test_helper'" at the head. eg.
require 'test_helper'
class AdminUserTest < ActiveSupport::TestCase
# test "the truth" do
# assert true
# end
end