Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AssociationTypeMismatch and FactoryGirl

This has been causing some frustration recently...

It seems that using Factories in my cucumber tests, in some situations causes AssociationTypeMismatch errors such as:

MyModel(#65776650) expected, got MyModel(#28190030) (ActiveRecord::AssociationTypeMismatch)

These seem to happen when there is an association reference - as if the Factory created object is different to the real one. See this question for more details: Cucumber duplicate class problem: AssociationTypeMismatch

I have been gradually changing Factory calls to real Model.create or mock_model calls. It would be nice to keep using Factory girl... I wonder if there is something I may have done wrong?

Thank you

like image 246
Adamski Avatar asked Feb 28 '11 17:02

Adamski


2 Answers

I had this happening with me on Rails 3.1.0 rc5, and got it working.

To expand on Jonas' answer.

You should change your Gemfile to be like this:

gem 'factory_girl', '~> 2.0.0', :require => false
gem 'factory_girl_rails', '~> 1.1.0', :require => false

And then if you are using Spork, make your spec/spec_helper.rb file look like this:

Spork.each_run do
 require 'factory_girl'
 require 'factory_girl_rails'
end
like image 172
staackuser2 Avatar answered Sep 17 '22 09:09

staackuser2


It seems to happen if ActiveSupport unloads and reloads a constant that you have a reference to. I've experienced the same with Rspec/Capybara, and what helped was a mixture of different things:

  • Make sure you have cached_classes set to false in your test environment (config/environments/test.rb)
  • In your gemspec, try replacing require 'factory_girl_rails' with 'factory_girl'

I'm using Spork (a test server), which seems to make this stuff increasingly difficult. If you are using a test server, evaluate whether you should put ', :require => false' after factory_girl in your gemspec.

The topic is also covered in this google groups thread

Please let us know if any of this helped.

like image 42
Jonas Bylov Avatar answered Sep 17 '22 09:09

Jonas Bylov