Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using fixtures with factory_girl

When building the following factory:

Factory.define :user do |f|
  f.sequence(:name) { |n| "foo#{n}" }
  f.resume_type_id { ResumeType.first.id }
end

ResumeType.first returns nil and I get an error.

ResumeType records are loaded via fixtures. I checked using the console and the entries are there, the table is not empty.

I've found a similar example in the factory_girl mailing list, and it's supposed to work.

What am I missing? Do I have to somehow tell factory_girl to set up the fixtures before running the tests?

This is what my test_helper looks like:

ENV["RAILS_ENV"] = "test"
require File.expand_path(File.dirname(__FILE__) + "/../config/environment")
require 'test_help'

class ActiveSupport::TestCase
  self.use_transactional_fixtures = true
  self.use_instantiated_fixtures  = false
  fixtures :all
end
like image 689
deb Avatar asked Apr 28 '10 19:04

deb


1 Answers

My solution to this was to create a db/seeds.rb file which contained model code to generate my seed data:

# Create the user roles
Role.create(:name => "Master", :level => 99)
Role.create(:name => "Admin", :level => 80)
Role.create(:name => "Editor", :level => 40)
Role.create(:name => "Blogger", :level => 30)
Role.create(:name => "User", :level => 0)

And then include it in my spec_helper.rb:

ENV["RAILS_ENV"] = 'test'
require File.expand_path(File.join(File.dirname(__FILE__),'..','config','environment'))
require 'spec/autorun'
require 'spec/rails'
require "#{Rails.root}/db/seeds.rb"

(To be fair, I haven't managed to get autospec to play nice with this yet as it keeps duplicating my seed data, but I haven't tried all that hard either.)

This also has the benefit of being Rails 3 ready and working with the rake db:seed task.

like image 106
Josh Avatar answered Oct 18 '22 03:10

Josh