2

我在 Rails 应用程序中有以下对象结构:

# app/models/model_a/model_b/model_c.rb
class ModelA < ActiveRecord::Base
  class ModelB < ActiveRecord::Base
    class ModelC < ActiveRecord::Base
    end
  end
end

# app/presenters/model_a/model_b/presenter_for_model_c.rb
class ModelA::ModelB::PresenterForModelC
end

现在,当我想用​​ RSpec 单独测试 PresenterForModelC 时,我不想require 'spec_helper'为了快速运行测试(à la Corey HainesGary Bernhardt),所以我试图直接加载我的演示者:

# spec/presenters/model_a/model_b/presenter_for_model_c_spec.rb
require_relative '../../../app/presenters/model_a/model_b/presenter_for_model_c'
describe ModelA::ModelB::PresenterForModelC do
end

但是,这失败了:

uninitialized constant ModelA (NameError)

我不能只创建一个存根结构,例如:

# spec/presenters/model_a/model_b/presenter_for_model_c_spec.rb
class ModelA
  class ModelB
  end
end
require_relative '../../../app/presenters/model_a/model_b/presenter_for_model_c'

因为当我运行完整套件时这会导致问题,因为加载模型时类不会从同一个父级继承。同样,我不能使用模块(出于同样的原因)。我也想避免:

# spec/presenters/model_a/model_b/presenter_for_model_c_spec.rb
class ModelA < ActiveRecord::Base
  class ModelB < ActiveRecord::Base
  end
end
require_relative '../../../app/presenters/model_a/model_b/presenter_for_model_c'

因为现在这将迫使我需要 ActiveRecord,这将违背快速规范的目的。

我想出的唯一其他解决方案是将演示者移动到它自己的命名空间Presenters::ModelA::ModelB::PresenterForModelC,其中Presenters::ModelAPresenters::ModelB是模块而不是类。这种方法的缺点是我必须创建一个目录app/presenters/presenters才能使自动加载工作,我认为这看起来有点乱。

还有其他选择吗?

4

0 回答 0