Ruby模块内类的RSpec测试应置于模块内还是外部?
模块内Ruby类的RSpec测试代码放置位置问题
我正在编写一个包含模块内类的Ruby程序,对应的RSpec测试代码应该放在模块内部还是外部?以下是两种写法的示例:
测试代码置于模块外的示例
# file: lib/calculator.rb module Computation class Calculator def add(x,y) return x+y end end end
# file: spec/calculator_spec.rb require_relative '../lib/calculator' RSpec.describe Computation::Calculator do it 'should add two numbers' do calc = Computation::Calculator.new expect(calc.add(1,2)).to eql(3) end end
测试代码置于模块内的示例
# file: spec/calculator_spec.rb require_relative '../lib/calculator' module Computation RSpec.describe Calculator do it 'should add two numbers' do calc = Calculator.new expect(calc.add(1, 2)).to eql(3) end end end
哪种方式更优?是否存在社区约定?两种写法有区别吗?
功能上无区别
两种写法都能正常运行测试,Ruby的常量查找机制会确保模块内的写法能正确找到Calculator类,模块外的写法则是直接通过完整命名空间引用,本质都是指向同一个类。社区更倾向模块外的写法
这是Ruby社区的主流约定,原因包括:
- 测试目标更明确:通过
RSpec.describe Computation::Calculator能直接看出测试的是哪个类,无需嵌套模块去推断 - 代码更简洁:避免不必要的模块嵌套,减少层级复杂度,让测试代码更易读
- 符合常规实践:绝大多数开源Ruby项目的RSpec测试都会采用直接引用完整命名空间的写法
- 模块内写法的适用场景
如果你的项目有大量同模块下的类需要测试,且希望测试代码的目录/命名空间结构和业务代码完全对齐,模块内的写法也可以使用,但这属于小众场景,并非主流选择。
内容的提问来源于stack exchange,提问作者StaticMethod
相关产品推荐
相关产品推荐

