I’ve refactored part of my test suite to not load rails when performing tests. The code below is an example of a test file that loads only selection pieces of Rails. It also fakes the “project” class. My problem is that this faked project class ends up overriding the normal project class and all other tests that involve the project class now fail.
How do I un-override my project class after this test file runs?
require 'active_model'
require 'active_model/validations'
require 'active_record/callbacks'
require 'active_support/core_ext/string'
class Project
include ActiveModel::Validations
include ActiveRecord::Callbacks
def initialize(attributes = {})
@general_media = attributes[:general_media]
end
attr_accessor :general_media
end
require_relative '../../../app/models/project/media.rb'
UPDATE: I think this comes close to what I need, except that I’m getting an error about Project being an uninitialized constant. I must be instantiating this test class incorrectly.
require 'active_model'
require 'active_model/validations'
require 'active_record/callbacks'
require 'active_support/core_ext/string' #used for '.blank?' method
require_relative '../../../app/models/project/media.rb'
describe Project::Media do
before(:all) do
class Project
include ActiveModel::Validations
include ActiveRecord::Callbacks
def initialize(attributes = {})
@general_media = attributes[:general_media]
end
attr_accessor :general_media
end
end
after(:all) { Object.send(:remove_const, :Project) }
#then all the tests
You should be able to un-define a class with
Module#remove_const.Its a private method so you’ll need to use
sendrather than a regular method call.UPDATE:
Perhaps try the following:
You will need to declare the Project class before the describe block if the subject depends on it. Also assuming your
Mediamodel depends on it before you require that.Later tests for the Project class will need to reload it, assuming they are separate tests you can just
requireyour project model class in that test file if you want a minimal (fast) test, or via the normal spec_helper if you want to load the whole Rails application (slow).As discussed in comments it might be easier to simply stub out the Project class rather than redefine it.