【问题标题】:reload class with dynamic mixin in rspec在 rspec 中使用动态 mixin 重新加载类
【发布时间】:2013-12-06 02:28:52
【问题描述】:

我有以下型号

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

但是,在运行 rspec 测试时,在第一个 Chicken 使用性别初始化后,通信方法会被缓存,并且所有 Chicken 都会独立于其性别说出相同的内容,即使在 config/environments/test.rb 中将 cache_classes 设置为 false

如何在测试执行期间重新加载 Chicken 类或修改此代码以消除此问题?

【问题讨论】:

  • 您将其发送给班级,而您实际上只想将其发送给实例。

标签: ruby-on-rails ruby rspec code-caching


【解决方案1】:

我决定改用单表继承 (http://api.rubyonrails.org/classes/ActiveRecord/Base.html#label-Single+table+inheritance),希望能解决这个问题。

【讨论】:

    猜你喜欢
    • 2012-12-31
    • 2011-05-14
    • 1970-01-01
    • 2013-04-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-29
    相关资源
    最近更新 更多