Different load order in rails console vs rspec tests?

I’ve written a simple module to extend ActiveRecord::Base, which works
fine in the rails console but fails miserably in rspec tests. The
intended usage looks like this:

class Premise < ActiveRecord::Base
has_my_extensions
end

I’ve traced it down to the fact that in the console, it loads
lib/my_extensions.rb before it loads premise.rb. In rspec, it’s
attempting to load premise.rb without loading my_extensions.rb, which
(naturally) results in a method_missing error.

(A) has anyone else seen this?
(B) what’s the proper remedy?

Details below the sig. Thanks…

  • ff

Some particulars: Ruby 1.9.2. Rails 3.0.3. RSpec 2.4.0.

=== file: $ROOT/config/environment.rb
require File.expand_path(’…/application’, FILE)
Demo::Application.initialize!
require ‘my_extensions’
=== EOF

=== file: $ROOT/app/models/premise.rb
$stderr.puts(Rails.logger.debug("==== loading #{FILE}"))
class Premise < ActiveRecord::Base
has_my_extensions
def test_one
extension_one
end
end
=== EOF

=== file: $ROOT/lib/my_extensions.rb hews to a familiar pattern:
$stderr.puts(Rails.logger.debug("==== loading #{FILE}"))
module MyExtensions
def self.included(base)
base.extend(ClassMethods)
end

module ClassMethods
def has_my_extensions
send(:include, InstanceMethods)
end
end

module InstanceMethods
def extension_one
$stderr.puts(Rails.logger.debug("==== extension_one"))
end
end
end

ActiveRecord::Base.send(:include, MyExtensions)
=== EOF

On Jan 28, 11:17pm, Fearless F. [email protected] wrote:

attempting to load premise.rb without loading my_extensions.rb, which
(naturally) results in a method_missing error.

(A) has anyone else seen this?
(B) what’s the proper remedy?

Don’t stick things at the bottom of environment.rb - when class
caching is turned on, rails will load models before you get there.
Stuff like this belongs in an initializer.

Fred

Frederick C. wrote in post #978281:

Stuff like this belongs in an initializer.

I’m just now realizing how environment.rb has changed in Rails3. Next
question: where does one learn the zen of initializers? Do I create my
own, e.g. $ROOT/config/initializers/my_extensions.rb? And is it
stylistically correct to stick something like “require ‘my_extensions’”
in an initializer file?

Thanks.

Fearless F. wrote in post #978285:

… Do I create my
own, e.g. $ROOT/config/initializers/my_extensions.rb?

FWIW, I simply created a $ROOT/config/initializers/my_extensions.rb file
and populated it with:

require ‘my_extensions’

… and rspec is all happy. Let me know if that’s not the right way to
go. Thanks for getting me pointed in the right direction.

  • ff

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs