开发者

Using fixtures with factory_girl

开发者 https://www.devze.com 2022-12-29 01:08 出处:网络
When building the following factory: Factory.define :user do |f| f.sequence(:name) { |n| \"foo#{n}\" } f.resume_t开发者_运维百科ype_id { ResumeType.first.id }

When building the following factory:

Factory.define :user do |f|
  f.sequence(:name) { |n| "foo#{n}" }
  f.resume_t开发者_运维百科ype_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


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.


Another option is to add seed.rb in your test or spec directory and require it in your helper file before your factories:

require File.expand_path(File.dirname(__FILE__) + "/seed")
require File.expand_path(File.dirname(__FILE__) + "/factories")

Rails 2.3

0

精彩评论

暂无评论...
验证码 换一张
取 消