Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rack::Test resulting in ActiveRecord::AssociationTypeMismatch

I have a problem when running all of my specs.

    ActiveRecord::AssociationTypeMismatch:
       Affiliate(#2154746360) expected, got Affiliate(#2199508660)

It would appear that my models are being loaded twice.

I have isolated the problem to be introduced with Rack::Test's requirement to define an "app" method.

require 'rack/test'
include Rack::Test::Methods

# app method is needed for rack-test
def app
  Rails.application
end

If I comment out Rails.application my rack specs do not work, but all of my other specs work fine. The use of Rails.application in the "app" method introduces the error above.

If I run my specs individually, everything works. I am preloading my environment with Spork and I think that the models are loaded first by Spork and then they are redefined when Rails.application is called in my "app" method.

Any ideas on how I can resolve this problem? I am not sure if there is another way to set my Rails app in the "app" method.

like image 973
Sean McCleary Avatar asked Apr 01 '11 22:04

Sean McCleary


1 Answers

From source code for Rails.application:

# File railties/lib/rails.rb, line 34
def application
  @@application ||= nil
end

This means that Rails.application returns the same object every time. Maybe this is the problem - running multiple tests on the same Rails app clashes with objects.

Some tutorials set tests up like this:

def app
  Rails::Application
end

Whereas others do it like this:

def app
  ActionController::Dispatcher.new
end

Both of which create new object for each call to app.

EDIT: Just noticed from logs that ActionController::Dispatcher.new is marked as deprecated.

like image 128
Laas Avatar answered Nov 15 '22 19:11

Laas