我在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 Haines或{{3} }),所以我试图直接加载我的演示者:
# 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::ModelA
和Presenters::ModelB
将是模块而不是类。这种方法的缺点是,我必须创建一个目录app/presenters/presenters
才能使自动加载工作,我认为这看起来有点混乱。
还有其他选择吗?