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.
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.
I am no longer having this problem anymore. I updated my gems. Rails was updated from 3.0.5 to 3.0.7 and I would guess that may have been the gem update that fixed my problem. Either way with newer versions of gems, my problem is fixed.
精彩评论