reload class with dynamic mixin in rspec

457 views Asked by At

i have following model

class Chicken < ActiveRecord::Base

  after_initialize :grow_up

  def grow_up
    if gender == "female"
      self.class.send(:include, Hen)
    elsif gender == "male"
      self.class.send(:include, Rooster)
    end
  end

end

module Hen

   def communicate
     "cluck cluck!"
   end

end

module Rooster

   def communicate
     "cock-a-doodle-doo!"
   end

end

However, while running rspec tests, after first Chicken is initialized with gender, communicate method becomes cached and all Chicken say the same independently of their gender, even though cache_classes is set to false in config/environments/test.rb

How can I reload Chicken class during tests execution or modify this code to remove this problem?

1

There are 1 answers

0
Pavel K. On

I decided to switch to single table inheritance instead (http://api.rubyonrails.org/classes/ActiveRecord/Base.html#label-Single+table+inheritance), which will hopefully solve this problem.