Rake db:migrate and Factory Girl weirdness

Today in my rails project, I needed to blow away my dev database and recreate it from scratch. Usually this isn’t a problem but all of the sudden I was getting this weird error message:

Mysql::Error: Table 'dev.service_codes' doesn't exist: SHOW FIELDS FROM `service_codes`

…service_codes being one of my tables. What struck me funny was that this was absolutely true – of course the table was missing – I just blew it away!

It took running a “rake db:migrate –trace” to find the exact offending line. Buried in the stack trace was a line that pointed to one of my Factory Girl test factories, that looks like so:

Factory.define :order do |f|
  f.franchise_id 1
  f.service_code_id ServiceCode.first
  f.update_reason "New Test Order"
  f.updated_at Time.now
  f.updated_by 0

For some reason, the rake migrate task was trying to compile all the code, including my test factories. It was looking at line 3 and saying “Hey! I can’t instantiate that ServiceCode object because the table doesn’t exist!”

Google and StackOverflow to the rescue. I found this related question and answer. Turns out in your Factory Girl code you need to do the following to keep this from throwing an error:

  f.service_code_id {ServiceCode.first}

Notice the braces around my object that may, or may not, exist. Now the migration runs fine.

I’ve very confused though. This is the second time in as many days that things that had previously worked without any trouble, started throwing errors. I haven’t updated ruby, rails, or even reloaded all my gems. I’ve deleted and remigrated my dev database hundreds of times, so much that I have a shell script to delete, migrate, and re-seed. Until today, this FactoryGirl issue has never bit me before.

1 lonely comment
Comments are closed for this post.
Good luck next time.